PowerShell Control Structures
Control structures are the "brain" of a program, determining under what conditions code executes, whether it repeats, and how to handle errors gracefully.
As a modern scripting language, PowerShell provides complete flow control syntax, including:
- Conditional statements:
if、elseif、else、switch - Loop structures:
for、foreach、while、do-while - Error handling mechanisms:
try-catch-finally
1. Conditional Statements
if / elseif / else
Basic syntax:
if (条件1) {
# 条件1为真执行
} elseif (条件2) {
# 条件2为真执行
} else {
# 其他情况
}
Example: Checking if Disk Space Is Insufficient
$disk = Get-PSDrive C
if ($disk.Free -lt 5GB) {
Write-Output "磁盘空间不足!"
} elseif ($disk.Free -lt 10GB) {
Write-Output "磁盘空间偏低。"
} else {
Write-Output "磁盘空间充足。"
}
switch
When there are multiple possible values to evaluate,switchis more readable than multipleif[if] statements.
switch ($value) {
"start" { Write-Output "开始任务" }
"stop" { Write-Output "停止任务" }
"exit" { Write-Output "退出程序" }
default { Write-Output "未知命令" }
}
Supports matching patterns:
switch -Wildcard ($filename) {
"*.txt" { "文本文件" }
"*.jpg" { "图片文件" }
default { "其他类型" }
}
2. Loop Structures
forfor Loop (Classic Counting Loop)
for ($i = 1; $i -le 5; $i++) {
Write-Output "第 $i 次"
}
foreachforeach Loop (Iterating Collections)
$names = "张三", "李四", "王五"
foreach ($name in $names) {
Write-Output "你好,$name"
}
You can also useForEach-Objectthe pipeline version:
$names | ForEach-Object { Write-Output "你好,$_" }
whilewhile Loop (Execute While Condition is True)
$count = 0
while ($count -lt 3) {
Write-Output "计数:$count"
$count++
}
do-whileanddo-until
doThe do-while loop willexecute at least once:
$count = 0
do {
Write-Output "当前值:$count"
$count++
} while ($count -lt 3)
do-until: it only stops when the condition becomes true
$count = 0
do {
Write-Output "当前值:$count"
$count++
} until ($count -ge 3)
3. Error Handling: try / catch / finally
PowerShell provides a structured exception handling mechanism for catching and responding to runtime errors.
3.1 Basic Structure
try {
# 尝试运行可能出错的代码
}
catch {
# 错误时执行
}
finally {
# 无论是否出错,都会执行(可选)
}
Example: Handling Division by Zero Errors
try {
$result = 10 / 0
}
catch {
Write-Output "发生错误:$($_.Exception.Message)"
}
finally {
Write-Output "运算结束"
}
Catching Specific Exception Types
try {
Get-Content "不存在的文件.txt"
}
catch [System.IO.FileNotFoundException] {
Write-Output "文件未找到!"
}
catch {
Write-Output "其他错误:$($_.Exception.Message)"
}
By default, some commands only print errors and do not enter thecatchblock. In this case, you need to add a parameter:
Remove-Item "不存在的文件.txt" -ErrorAction Stop
or set a global policy:
$ErrorActionPreference = "Stop"
4. Summary
| Control Structure | Function | Applicable Scenario |
|---|---|---|
if / else |
Evaluate one or more conditions | Check disk, status, etc. |
switch |
Multi-branch evaluation (value or pattern matching) | Command parsing, classification |
for |
Finite iteration count | When the number of iterations is known |
foreach |
Traverse arrays or collections | User lists, file lists, etc. |
while |
Execute while the condition is true | Wait for a certain state or change |
do-while |
Execute at least once | Initial validation + retry mechanism |
try-catch |
Catch runtime errors to prevent script interruption | File operations, network requests, etc. |
finally |
Cleanup resources, print logs, and other ending operations | Ensure a certain block of code always executes |
5. Practice Tasks
Task 1: Determine whether a number is even or odd
$number = 7
if ($number % 2 -eq 0) {
"偶数"
} else {
"奇数"
}
Task 2: Traverse an array and print the length of each item
$items = "apple", "banana", "cherry"
foreach ($item in $items) {
"$item 的长度是 $($item.Length)"
}
Task 3: Handle file read errors
try {
Get-Content "D:\not-exist.txt"
}
catch {
"文件读取失败:" + $_.Exception.Message
}
Other Extensions