首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

PowerShell 深度探索(七):變數與資料類型基礎

     編輯:關於.NET

變數基礎

PowerShell 變數以 $ 開頭,使用 = 指派:

$StrUser = "MR"
Set-Variable -Name StrUser -Value "MaRui"  # 等效指令(名稱不需 $)

系統保留字(不可作為變數名)

break, continue, do, else, elseif, filter, foreach, function, if, in, return, switch, until, where, while

輸出變數值

Write-Output $StrUser
$StrUser  # 直接輸入變數名亦可輸出

變數輸出示範

常見資料類型

類型.NET 對應說明
[int]System.Int3232 位元有號整數
[long]System.Int6464 位元有號整數
[double]System.Double64 位元雙精度浮點
[single]System.Single32 位元單精度浮點
[string]System.StringUnicode 字串
[char]System.Char16 位元 Unicode 字元
[byte]System.Byte8 位元無號整數
[decimal]System.Decimal128 位元十進制精確數值
[array]System.Array陣列
[xml]System.Xml.XmlDocumentXML 文件
[hashtable]System.Collections.Hashtable雜湊表
[bool]System.Booleantrue/false

字串操作

串接

$strA = "Hello "
$strB = "World!"
$strC = $strA + $strB  # "Hello World!"

字串串接

取代

$strA = "hi! world!"
$strB = $strA -replace "hi!", "Hello"  # "Hello world!"

字串取代

引用展開差異

$strA = "MaRui"
"This is $strA."   # 雙引號:展開變數 → "This is MaRui."
'This is $strA.'   # 單引號:字面值 → "This is $strA."

引用展開差異

數值運算

5 + 100           # 105
$x = 200 + 1      # 201
[int]$y = (7 + 13 * 2) / 10  # 3(整數除法截斷)

數值運算示範

運算子對照

運算子功能
+加法 / 字串串接
-減法
*乘法
/除法
%取餘數
++遞增 1
--遞減 1

括號 () 可控制優先順序。

強型別宣告重要性

PowerShell 雖具動態型別推斷,但腳本開發時建議明確宣告型別:

  • 避免非預期型別轉換導致邏輯錯誤
  • 提升程式碼可讀性與維護性
  • 參數驗證可在進入函數前攔截錯誤
# 建議寫法
[int]$count = 0
[string[]]$names = @("A", "B")
[hashtable]$config = @{ Key = "Value" }

特殊自動變數

  • $_:管線目前物件 / ForEach-Object 迴圈變數
  • $Args:函數/腳本未命名參數陣列
  • $Error:錯誤記錄陣列
  • $Home:使用者家目錄
  • $PSHome:PowerShell 安裝目錄
  • $True/$False/$Null:布林與空值常數

總結

變數與資料類型是 PowerShell 程式設計的基石。理解型別系統、字串展開規則、數值運算特性,並養成強型別宣告習慣,能顯著減少執行期錯誤,編寫出更專業的自動化腳本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved