第 6 章
變數、陣列、字串與基本資料處理
本章重點
- 學會宣告與使用變數
- 認識常用資料型別
- 操作陣列與字串
- 用運算子做基本計算與比較
變數
PowerShell 的變數以 $ 開頭,不需要事先宣告型別:
# 宣告變數
$name = "PowerShell"
$count = 10
$price = 99.5
$isReady = $true
# 使用變數
Write-Output "你好,$name"
Write-Output "數量:$count"
# 查看變數型別
$count.GetType().Name # 輸出:Int32
$name.GetType().Name # 輸出:String
字串內插:
用雙引號
"..." 包住字串時,$變數 會被自動替換成值。
用單引號 '...' 則不會,原樣輸出。
常用資料型別
# 字串(String)
$msg = "Hello"
# 整數(Int)
$num = 42
# 浮點數(Double)
$pi = 3.14
# 布林值(Boolean)
$flag = $true
$flag = $false
# 空值
$nothing = $null
# 強制指定型別
[int]$x = "123" # 轉換為整數
[string]$s = 456 # 轉換為字串
陣列
# 建立陣列
$fruits = @("apple", "banana", "cherry")
# 取得元素(從 0 開始)
$fruits[0] # apple
$fruits[2] # cherry
$fruits[-1] # cherry(最後一個)
# 取得陣列長度
$fruits.Count # 3
# 加入元素
$fruits += "grape"
# 遍歷陣列
foreach ($fruit in $fruits) {
Write-Output $fruit
}
字串操作
$text = "Hello, PowerShell!"
# 長度
$text.Length # 18
# 轉大小寫
$text.ToUpper() # HELLO, POWERSHELL!
$text.ToLower() # hello, powershell!
# 取代
$text.Replace("Hello", "Hi") # Hi, PowerShell!
# 切割
$text.Split(",") # 分成 @("Hello", " PowerShell!")
# 是否包含
$text.Contains("Power") # True
# 去除前後空白
" hello ".Trim() # "hello"
# 取子字串(從第 0 個字元,取 5 個)
$text.Substring(0, 5) # Hello
比較運算子
# 數值比較
5 -eq 5 # True(等於)
5 -ne 3 # True(不等於)
5 -gt 3 # True(大於)
5 -lt 10 # True(小於)
5 -ge 5 # True(大於等於)
5 -le 10 # True(小於等於)
# 字串比較(不分大小寫)
"hello" -eq "HELLO" # True
"hello" -like "hel*" # True(萬用字元比對)
"hello" -match "^hel" # True(正則表達式)
常見錯誤:
不要用
== 來比較,PowerShell 用 -eq。
$a = 5 是賦值,$a -eq 5 才是比較。
小練習:
- 建立一個
$name變數存你的名字,用Write-Output輸出 "你好,$name" - 建立陣列
$nums = @(10, 20, 30, 40, 50),輸出第三個元素 - 用
$nums.Count確認長度 - 試試
"PowerShell".ToUpper()
小結
變數以 $ 開頭,不需要宣告型別。
陣列用 @() 建立,從 0 開始索引。
字串有許多內建方法,比較用 -eq、-like 等運算子。
下一章,用這些基礎來寫條件判斷與迴圈。