控制结构是程序的"大脑",决定代码在什么条件下执行、是否重复执行,以及如何优雅地处理错误。
PowerShell 作为现代脚本语言,提供了完整的流程控制语法,包括:
条件语句:if
、elseif
、else
、switC++h
循环结构:for
、foreach
、while
、do-while
错误处理机制:try
-catch
-finally
if
/ elseif
/ else
基本语法:
if (条件1) { # 条件1为真执行} elseif (条件2) { # 条件2为真执行} else { # 其他情况}
$disk = Get-PSDrive Cif ($disk.Free -lt 5GB) { Write-Output "磁盘空间不足!"} elseif ($disk.Free -lt 10GB) { Write-Output "磁盘空间偏低。"} else { Write-Output "磁盘空间充足。"}
switch
当有多个可能值要判断时,switch
比多个 if
更清晰。
switch ($value) { "start" { Write-Output "开始任务" } "stop" { Write-Output "停止任务" } "exit" { Write-Output "退出程序" } default { Write-Output "未知命令" }}
支持匹配模式:
switch -Wildcard ($filename) { "*.txt" { "文本文件" } "*.jpg" { "图片文件" } default { "其他类型" }}
for
循环(经典计数循环)for ($i = 1; $i -le 5; $i++) { Write-Output "第 $i 次"}
foreach
循环(遍历集合)$names = "张三", "李四", "王五"foreach ($name in $names) { Write-Output "你好,$name"}
也可使用 ForEach-Object
管道版本:
$names | ForEach-Object { Write-Output "你好,$_" }
while
循环(条件为真执行)$count = 0while ($count -lt 3) { Write-Output "计数:$count" $count++}
do-while
与 do-until
do
循环会 至少执行一次:
$count = 0do { Write-Output "当前值:$count" $count++} while ($count -lt 3)
do-until
:直到条件为真才停止
$count = 0do { Write-Output "当前值:$count" $count++} until ($count -ge 3)
PowerShell 提供结构化异常处理机制,用于捕获和响应运行时错误。
$disk = Get-PSDrive Cif ($disk.Free -lt 5GB) { Write-Output "磁盘空间不足!"} elseif ($disk.Free -lt 10GB) { Write-Output "磁盘空间偏低。"} else { Write-Output "磁盘空间充足。"}0
$disk = Get-PSDrive Cif ($disk.Free -lt 5GB) { Write-Output "磁盘空间不足!"} elseif ($disk.Free -lt 10GB) { Write-Output "磁盘空间偏低。"} else { Write-Output "磁盘空间充足。"}1
$disk = Get-PSDrive Cif ($disk.Free -lt 5GB) { Write-Output "磁盘空间不足!"} elseif ($disk.Free -lt 10GB) { Write-Output "磁盘空间偏低。"} else { Write-Output "磁盘空间充足。"}2
默认一些命令只会打印错误,不会进入 或设置全局策略: 任务 1:判断一个数字是否为偶数或奇数 任务 2:遍历数组并打印每项长度 任务 3:处理文件读取错误catch
。此时需要添加参数:$disk = Get-PSDrive Cif ($disk.Free -lt 5GB) {
Write-Output "磁盘空间不足!"} elseif ($disk.Free -lt 10GB) {
Write-Output "磁盘空间偏低。"} else {
Write-Output "磁盘空间充足。"}3
$disk = Get-PSDrive Cif ($disk.Free -lt 5GB) {
Write-Output "磁盘空间不足!"} elseif ($disk.Free -lt 10GB) {
Write-Output "磁盘空间偏低。"} else {
Write-Output "磁盘空间充足。"}4
四、小结
控制结构 功能 适用场景 if
/ else
判断一个或多个条件 判断磁盘、状态等 switch
多分支判断(值或模式匹配) 命令解析、分类 for
有限次数迭代 明确循环次数 foreach
遍历数组或集合 用户列表、文件列表等 while
条件为真时执行 等待某状态或变化 do-while
至少执行一次 初次验证 + 重试机制 try-catch
捕获运行错误,防止脚本中断 文件操作、网络请求等 finally
清理资源、打印日志等结尾操作 保证某块代码始终执行 五、练习任务
$disk = Get-PSDrive Cif ($disk.Free -lt 5GB) {
Write-Output "磁盘空间不足!"} elseif ($disk.Free -lt 10GB) {
Write-Output "磁盘空间偏低。"} else {
Write-Output "磁盘空间充足。"}5
$disk = Get-PSDrive Cif ($disk.Free -lt 5GB) {
Write-Output "磁盘空间不足!"} elseif ($disk.Free -lt 10GB) {
Write-Output "磁盘空间偏低。"} else {
Write-Output "磁盘空间充足。"}6
$disk = Get-PSDrive Cif ($disk.Free -lt 5GB) {
Write-Output "磁盘空间不足!"} elseif ($disk.Free -lt 10GB) {
Write-Output "磁盘空间偏低。"} else {
Write-Output "磁盘空间充足。"}7