PowerShell Control Structures
Control structures are the 'brain' of a program, determining under what conditions code executes, whether it repeats, and how to gracefully handle errors.
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 mechanism:
try-catch-finally
I. Conditional Statements
if / elseif / else
Basic syntax:
if (条件1) {
# Execute if condition 1 is true
} elseif (条件2) {
# Execute if condition 2 is true
} else {
# Other cases
}
Example: Check whether 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 judge,switch is clearer than multiple 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 { "其他类型" }
}
II. Loop Structures
for loop (classic counting loop)
for ($i = 1; $i -le 5; $i++) {
Write-Output "第 $i 次"
}
foreach loop (iterating over a collection)
$names = "张三", "李四", "王五"
foreach ($name in $names) {
Write-Output "你好,$name"
}
You can also use ForEach-Object the pipeline version:
$names | ForEach-Object { Write-Output "你好,$_" }
while loop (executes while condition is true)
$count = 0
while ($count -lt 3) {
Write-Output "计数:$count"
$count++
}
do-while The difference between do-until
do A loop will execute at least once:
$count = 0
do {
Write-Output "当前值:$count"
$count++
} while ($count -lt 3)
do-until: it stops only when the condition becomes true
$count = 0
do {
Write-Output "当前值:$count"
$count++
} until ($count -ge 3)
III. Error Handling: try / catch / finally
PowerShell provides a structured exception handling mechanism for catching and responding to runtime errors.
3.1 Basic Structure
try {
# Attempt to run potentially failing code
}
catch {
# execute on error
}
finally {
# Executes whether or not there is an error (optional)
}
Example: Handle a division-by-zero error
try {
$result = 10 / 0
}
catch {
Write-Output "发生错误:$($_.Exception.Message)"
}
finally {
Write-Output "运算结束"
}
Catch a specific exception type
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 Or set the global policy: Task 1: Determine whether a number is even or odd Task 2: Iterate over an array and print the length of each item Task 3: Handle file read errorsForce a command to throw an exception
catch. In this case you need to add the parameter:Remove-Item "不存在的文件.txt" -ErrorAction Stop
$ErrorActionPreference = "Stop"
IV. Summary
Control structures
Function
Applicable scenarios
if / elseEvaluate one or more conditions
Check disk, status, and so on
switchMulti-branch judgment (value or pattern matching)
Command parsing and classification
forIterate a finite number of times
Define the number of loop iterations explicitly
foreachIterate over an array or collection
User lists, file lists, etc.
whileExecute while the condition is true
Wait for a certain state or change
do-whileexecute at least once
Initial validation plus a retry mechanism
try-catchCatch runtime errors to prevent script interruption
File operations, network requests, etc.
finallyCleanup operations such as releasing resources and printing logs
Ensure a certain block of code always executes
V. Practice Tasks
$number = 7
if ($number % 2 -eq 0) {
"偶数"
} else {
"奇数"
}
$items = "apple", "banana", "cherry"
foreach ($item in $items) {
"$item 的长度是 $($item.Length)"
}
try {
Get-Content "D:\not-exist.txt"
}
catch {
"文件读取失败:" + $_.Exception.Message
}