第 7 章
條件判斷與迴圈:讓 PowerShell 開始自動做事
本章重點
- 用
if / elseif / else做條件判斷 - 用
foreach遍歷集合 - 用
for跑固定次數的迴圈 - 用
while在條件成立時持續執行 - 認識
switch多條件判斷
if / elseif / else
$score = 75
if ($score -ge 90) {
Write-Output "優等"
} elseif ($score -ge 70) {
Write-Output "良好"
} elseif ($score -ge 60) {
Write-Output "及格"
} else {
Write-Output "不及格"
}
# 搭配 Test-Path
if (Test-Path "C:\mydata") {
Write-Output "資料夾存在"
} else {
New-Item "C:\mydata" -ItemType Directory
Write-Output "已建立資料夾"
}
foreach 迴圈
遍歷陣列或集合中的每一個元素:
$names = @("Alice", "Bob", "Charlie")
foreach ($name in $names) {
Write-Output "你好,$name"
}
# 搭配 Get-ChildItem,處理每個檔案
foreach ($file in Get-ChildItem .\*.txt) {
Write-Output $file.Name
}
# 管線寫法(ForEach-Object)
Get-ChildItem .\*.txt | ForEach-Object {
Write-Output $_.Name
}
$_ 是什麼?
在管線中,$_ 代表目前正在處理的那一個物件,類似「它」的意思。
for 迴圈
# 從 1 數到 5
for ($i = 1; $i -le 5; $i++) {
Write-Output "第 $i 次"
}
# 倒數
for ($i = 10; $i -gt 0; $i--) {
Write-Output $i
}
while 迴圈
$count = 0
while ($count -lt 5) {
Write-Output "目前計數:$count"
$count++
}
注意無限迴圈:
while 的條件永遠成立就會跑不停。
按 Ctrl + C 可以強制中斷執行中的指令。
switch 多條件判斷
$day = "Monday"
switch ($day) {
"Monday" { Write-Output "星期一" }
"Tuesday" { Write-Output "星期二" }
"Wednesday" { Write-Output "星期三" }
default { Write-Output "其他天" }
}
# switch 也可以比對數字範圍
$score = 85
switch ($score) {
{ $_ -ge 90 } { Write-Output "優等"; break }
{ $_ -ge 70 } { Write-Output "良好"; break }
default { Write-Output "待加強" }
}
小練習:
- 寫一個 if 判斷:如果
$num大於 0 輸出「正數」,小於 0 輸出「負數」,等於 0 輸出「零」 - 建立陣列
$cities = @("台北", "台中", "高雄"),用 foreach 逐一輸出 - 用 for 迴圈輸出 1 到 10 的偶數(提示:
$i % 2 -eq 0)
小結
條件判斷和迴圈是讓腳本「自動做事」的關鍵。
if 決定要不要做,foreach 讓你對每個物件做一樣的事,
for 和 while 控制重複次數。
下一章,把這些技巧放進腳本檔案裡。