蓝色天空.知识 · 实践 · 创造
我的收藏
PowerShell 教程目录 16章
PowerShell / LEARN BY DOING

PowerShell 控制结构:全部循环、switch与终止错误

逐分支验证条件、通配switch、循环次数及catch/finally行为。

学完这一章,你能够

  • 逐分支验证条件、通配switch、循环次数及catch/finally行为。
  • 逐分支验证条件、通配switch、循环次数及catch/finally行为。

条件和switch

if/elseif/else按条件顺序匹配,磁盘阈值演示使用固定3/7/12GiB分别走三个分支。switch可对集合匹配多个条款,-Wildcard与-Regex职责不同,break是否退出需明确,不套用C式自动单分支。

六种遍历方式

for计数、foreach语句、ForEach-Object管道、while、do-while及do-until都保留;do至少执行一次,while可能零次。固定样本验证输出,另展示break/continue与计数边界。

try、类型catch和finally

整数除零为终止错误可catch,缺文件的cmdlet一般需要-ErrorAction Stop;实际抛出的可能是ItemNotFoundException等,不应统一写FileNotFoundException。

默认非终止错误的继续、升级为Stop后的捕获和finally运行分别验证;finally用于清理,但进程被外部强杀等情况不能保证代码必然执行。Preference在局部保存恢复,不长期改变用户会话。

练习的可核对结果

7判奇数、三种水果长度、缺文件读取和有限重试分别实际运行;循环有上限,错误信息保留真实类型和阶段,不用预写成功文案覆盖失败。

知识、流程与适用条件

条目职责/含义条件与限制
if/elseif/else按次序分支3/7/12GiB分别验证
switch值/条件/通配/正则可多项命中,break显式
for计数循环1至5实际次数
foreach / ForEach-Object语句遍历 / 管道各自执行形态
while先判断可零次
do-while / do-until后判断至少一次,条件含义相反
break / continue结束/跳过明确目标循环
try/catch/finally终止错误/清理非终止需ErrorAction Stop
类型catch按真实异常ItemNotFound不强写成FileNotFound
Preference作用范围本例局部,不永久改用户会话

本章独立核心源码与验证步骤

含完整源码 · 23 行
展开查看收起
powershell
. (Join-Path $PSScriptRoot 'lab.ps1')
$branches=@(3GB,7GB,12GB|ForEach-Object {if($_ -lt 5GB){'low'}elseif($_ -lt 10GB){'middle'}else{'enough'}})
Assert-Learning (($branches -join ',') -eq 'low,middle,enough') 'all disk branches'
$switchValues=@(switch -Wildcard (@('a.txt','a.jpg','a.bin')) {'*.txt'{'text'} '*.jpg'{'image'} default{'other'}})
Assert-Learning (($switchValues -join ',') -eq 'text,image,other') 'wildcard switch branches'
$multi=@(switch ('abc') {'abc'{'exact'} {$_ -like 'a*'}{'pattern'}});Assert-Learning ($multi.Count -eq 2) 'switch can match multiple clauses'
$for=@(for($i=1;$i -le 5;$i++){$i});$foreach=@(foreach($s in @('apple','banana','cherry')){$s.Length});$pipeline=@('apple','banana','cherry'|ForEach-Object {$_.Length})
$while=@();$n=0;while($n -lt 3){$while+=,$n;$n++};$zero=0;while($false){$zero++};$once=0;do{$once++}while($false)
$dw=@();$n=0;do{$dw+=,$n;$n++}while($n -lt 3);$du=@();$n=0;do{$du+=,$n;$n++}until($n -ge 3)
Assert-Learning (($for -join ',') -eq '1,2,3,4,5' -and ($foreach -join ',') -eq '5,6,6' -and ($pipeline -join ',') -eq '5,6,6') 'for foreach pipeline'
Assert-Learning (($while -join ',') -eq '0,1,2' -and ($dw -join ',') -eq '0,1,2' -and ($du -join ',') -eq '0,1,2' -and $zero -eq 0 -and $once -eq 1) 'all loop conditions'
$skip=@(foreach($i in 1..6){if($i -eq 2){continue};if($i -eq 5){break};$i});Assert-Learning (($skip -join ',') -eq '1,3,4') 'break and continue'
$root=New-LearningDirectory
try {
 $divisionCaught=$false;$finallyRan=$false;try{$null=10/0}catch{$divisionCaught=$true}finally{$finallyRan=$true}
 Assert-Learning ($divisionCaught -and $finallyRan) 'division catch finally'
 $nonTerminatedCatch=$false;$continued=$false;try{Get-Item -LiteralPath (Join-Path $root 'absent') -ErrorAction SilentlyContinue;$continued=$true}catch{$nonTerminatedCatch=$true}
 Assert-Learning ($continued -and -not $nonTerminatedCatch) 'nonterminating error continues'
 $terminatingType='';try{Get-Item -LiteralPath (Join-Path $root 'absent') -ErrorAction Stop}catch [Management.Automation.ItemNotFoundException]{$terminatingType=$_.Exception.GetType().FullName}
 Assert-Learning ($terminatingType -eq 'System.Management.Automation.ItemNotFoundException') 'actual typed catch'
 Write-LearningReport 'powershell-control-structures' @{if_branches=$branches;switch_branches=$switchValues;switch_multi_count=$multi.Count;for=$for;foreach_lengths=$foreach;pipeline_lengths=$pipeline;while=$while;do_while=$dw;do_until=$du;while_false_times=$zero;do_false_times=$once;break_continue=$skip;division_caught=$divisionCaught;finally_ran=$finallyRan;nonterminating_continued=$continued;typed_error=$terminatingType;seven_is_odd=(7%2 -ne 0)}
}finally{Remove-LearningDirectory $root}

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

  • 所有条件、switch两种目标、六种循环、零次/至少一次、break/continue分别实测。
  • 除零、非终止继续、ItemNotFound类型catch及finally实际核对。

本章附件与实例包

下载课程关联工程包:PowerShell

课程关联工程包(登记关联16章) · 含当前章节或实例 · mbskycom202611a525.zip

常见错误与边界检查

  • 把累计CPU秒数写成百分比。
  • 把非终止错误、全局作用域或当前用户持久策略理解错。
  • 用本地替代冒充真实服务/远程/账户/SQL/Office通过。

技术规范与官方资料

练习与参考解答

查看参考解答

先发现命令和参数,分清类型/输出流/作用域;副作用限定在自己创建的目标,未具备的管理环境不标完成。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习