蓝色天空网mbsky.com · 知识 · 实践 · 创造PowerShell · 本地阅读预览
教程 / .NET / PowerShell

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

逐分支验证条件、通配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作用范围本例局部,不永久改用户会话

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

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}
PowerShell 控制结构:全部循环、switch与终止错误:本章独立本地实验

所需环境:Windows / PowerShell7.6.5 / 同包自有文件、进程、回环JSON;其它平台和管理环境待验

当前源码 SHA256:58b4c0b1d06455be0d2c5ecb7c17b481dd826eb6224eacfd5eb9b51642b08c01

下载本站示例源码
预期结果 · 待实际运行核验
  • 所有条件、switch两种目标、六种循环、零次/至少一次、break/continue分别实测。
  • 除零、非终止继续、ItemNotFound类型catch及finally实际核对。

常见错误与边界

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

练习与解答

仅在新建测试目录改变一个固定输入,先列出预期、目标及清理方式,再核对真实输出。

展开参考解答

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

规范与官方依据