PowerShell 第 5 课:健壮的脚本——错误、输出流与安全变更

“运行完了”不等于“成功了”。本课追踪一个错误从产生到被调度器读到退出码的全过程:终止与非终止错误、try/catch、原生程序、六个输出流、严格模式、-WhatIf/-Confirm、重试与结构化日志——并把 OpsKit 打造成一个可以安全修改系统状态的模块
PowerShell 7.6 LTS(7.6.10)对照 Bash 的 set -e / pipefail仅本机 · 免费已核实 · 2026-11-24
在学习路线中的位置 第 1 课讲了对象、管道以及带退出码的第一个脚本;第 2 课讲语言基础;第 3 课讲高级函数和 OpsKit v0.1(Get-OpsServer、Get-OpsConfig、Test-OpsEndpoint);第 4 课把它打包成真正的模块 OpsKit v0.2(OpsKit.psd1 / OpsKit.psm1,Public/ 与 Private/,发布到本地仓库)。到目前为止 OpsKit 只读取信息。本课开始让它修改状态,而从这一刻起错误处理就不再可有可无:OpsKit v0.3 新增 Invoke-OpsBackup(压缩 ~/pslab/data、保留最新 7 份、对被锁文件重试、JSON 行日志、完整支持 -WhatIf)、Remove-OpsBackup 以及通用的 Invoke-OpsRetry。如果你熟悉 Bash,可以把本课看作 PowerShell 版的 set -euo pipefail、trap、2>&1 和 “dry-run” 开关——更精确,也有它自己的陷阱。
总体学习目标
  • 把任何错误归类为非终止、语句终止或脚本终止错误,并预测接下来哪些代码还会执行——这是本课的核心动画;用 Get-Error 读懂 ErrorRecord(Exception、CategoryInfo、FullyQualifiedErrorId、TargetObject、InvocationInfo、ScriptStackTrace)。
  • 解释为什么 try { Get-Item missing.txt } 什么也捕获不到,用 -ErrorAction Stop 修复,编写按类型捕获的 catch 和 finally,并在 throw、Write-Error 与 $PSCmdlet.ThrowTerminatingError() 之间正确选择。
  • 正确处理原生程序:$LASTEXITCODE、$?、stderr 记录,以及 $PSNativeCommandUseErrorActionPreference 与 $ErrorActionPreference = 'Stop' 的配合——包括 robocopy 这类非零退出码也表示成功的程序。
  • 用 2>&1、3>、*>、6>&1、>$null 路由六个输出流;使用 Write-Verbose/-Debug/-Warning/-Information、首选项变量和 -XxxVariable 参数;理解为什么 Write-Host 属于第 6 流。
  • 开启 Set-StrictMode -Version Latest 并复现它能发现的问题(未初始化变量、不存在的属性——连哈希表键也算、方法调用语法、越界索引);编写守卫语句、验证特性和正确的 $null 比较。
  • 正确实现 SupportsShouldProcess:$PSCmdlet.ShouldProcess()、ConfirmImpact 与 $ConfirmPreference、-WhatIf 如何传递——以及经验证它不会传到 Compress-Archive 的情形。
  • 编写带指数退避和随机抖动、只重试瞬时的终止错误的 Invoke-OpsRetry;用 Wait-Job -Timeout、取消令牌和 Web cmdlet 超时限制等待时间;写 JSON 行日志;了解 Start-Transcript 会漏掉什么。
  • 交付 OpsKit v0.3:带轮转、-WhatIf、重试与日志的 Invoke-OpsBackup + Remove-OpsBackup;一个退出码有意义的夜间包装脚本;以及一个证明每条错误路径都正确的故障注入脚本。

1 小时时间分配

#时间模块核心内容动画 / 互动实验(~/pslab)
0课前准备:故障场景脚本OpsKit v0.2 → v0.3 目录结构、$env:OPSKIT_HOME、scripts/Show-ErrorKinds.ps1、清理 tmp/第 4 课热身问答从 ~/pslab/OpsKit 导入 OpsKit 0.3.0
100–06错误模型非终止、语句终止、脚本终止;$Error;ErrorRecord 结构;Get-Error;$?核心动画:一个错误会经历什么解剖一个真实的 ErrorRecord
206–13try / catch-ErrorAction、$ErrorActionPreference、按类型捕获、finally、throw / Write-Error / ThrowTerminatingError、trap、-ErrorVariable哪个 catch 块会执行?带三个类型化 catch 的 Read-Config
313–21原生命令$LASTEXITCODE、$?、stderr 变成 ErrorRecord、NativeCommandExitException、robocopy 退出码原生退出码路由git 与 cmd 失败、robocopy 陷阱
421–28输出流第 1–6 流、重定向运算符、首选项变量、-InformationVariable、Write-Host = 第 6 流输出流路由器分别捕获每个流
528–35严格模式Set-StrictMode -Version Latest、守卫语句、验证特性、$null -eq、在边界处设置 Stop严格模式检查器复现四个“静默缺陷”并逐一捕获
635–42安全变更SupportsShouldProcess、ShouldProcess()、ConfirmImpact、$ConfirmPreference、$WhatIfPreference、传递、幂等ShouldProcess 决策路径证明 -WhatIf 能传到哪里、传不到哪里
742–50重试、超时、日志Invoke-OpsRetry(退避 + 抖动)、Wait-Job -Timeout、CancellationToken、-TimeoutSec 与 -OperationTimeoutSeconds、JSON 行、会话记录重试时间线重试、超时、记录日志
850–60OpsKit v0.3Invoke-OpsBackup、Remove-OpsBackup、轮转、清理不完整归档、夜间包装脚本的退出码备份执行路径 + 排错决策树备份、轮转、锁定文件、读日志
—课后速查表 · 综合实验Test-OpsFailure.ps1:注入 8 种故障,检查退出码、归档文件和日志事件结业测验(12 题)8 个场景全部通过

知识覆盖矩阵 Knowledge Coverage Matrix

目标技能M1M2M3M4M5M6M7M8关键命令实验
对错误分类并读懂 ErrorRecord✓✓✓·✓··✓$Error[0]、Get-Error、FullyQualifiedErrorIdM1
捕获正确的错误✓✓✓·✓·✓✓-ErrorAction Stop、catch [Type]、finallyM2、综合实验
在自己的命令中报告错误·✓··✓·✓✓throw、Write-Error、$PSCmdlet.ThrowTerminatingError()M2、M8
原生程序退出码✓·✓✓···✓$LASTEXITCODE、$PSNativeCommandUseErrorActionPreferenceM3、综合实验
输出流与重定向·✓✓✓·✓✓·2>&1、*>、-InformationVariable、Write-VerboseM4
防御式编程与严格模式····✓✓·✓Set-StrictMode、[ValidateRange()]、$null -eq $xM5、M8
安全变更:-WhatIf / -Confirm / 幂等·····✓·✓SupportsShouldProcess、ShouldProcess()、ConfirmImpactM6、M8、综合实验
重试、超时与日志···✓··✓✓Invoke-OpsRetry、Wait-Job -Timeout、ConvertTo-Json -CompressM7、M8、综合实验

本课不包含的内容(以及去哪里学)

主题为什么不在本课去哪里学
远程计算机上的错误(Invoke-Command 逐台错误、PSComputerName)、作业错误处理的细节、ForEach-Object -Parallel 中的错误需要先掌握远程与运行空间第 6 课:远程管理、作业与并行运维
HTTP 错误处理:状态码、-SkipHttpErrorCheck、-MaximumRetryCount、限流(429)与 Retry-After属于 REST / 云自动化;本课只预览 Web 超时第 7 课(Invoke-OpsApi 复用 Invoke-OpsRetry)
用 Pester 测试错误路径(Should -Throw / Should-Throw)、PSScriptAnalyzer 规则(如 PSShouldProcess)、调试器质量工具第 8 课
类与自定义异常类型(class OpsException : Exception)很少需要:一个带好的 FullyQualifiedErrorId 的 ErrorRecord 通常就够了Everything you wanted to know about exceptions
Windows 事件日志 / syslog / OpenTelemetry 上报与平台相关;JSON 行是可移植的第一步你所用可观测性平台的文档

如何使用本资料

每个模块 10 个分页
原理 · 图解 · 动画 · 命令 · 实验 · 生产案例 · 排错 · 测验 · 语音 · 视频。模块 1 的动画(“一个错误会经历什么”)是整课的思维模型;后面任何输出让你意外时,回去再播放一遍。
学习进度
测验得分 ≥ 70%,或点击“标记本模块为已完成”,都会计入进度。进度保存在本浏览器的本地存储中(如果浏览器禁止本地存储,刷新后会重置)。
语音讲解
“语音”分页使用浏览器内置的 Web Speech API(zh-CN)朗读讲解稿。没有语音包时仍可阅读讲解稿,或交给其他 TTS 工具。
版本说明 2026-11-24 在 Windows 上的 PowerShell 7.6.10(.NET 10.0.15)核实。本课内容适用于 PowerShell 7.4+;$PSNativeCommandUseErrorActionPreference 在 7.4 成为正式(非实验)功能,默认值为 $false。从 7.2 起,原生程序的 stderr 不再把 $? 设为 $false,也不会触发 $ErrorActionPreference = 'Stop'——这与 Windows PowerShell 5.1 差别很大,在 5.1 中对原生命令使用 2>&1 可能让脚本停止。Get-Error 只存在于 7.x。实验机上的 Compress-Archive 来自 Microsoft.PowerShell.Archive 1.2.7(一个脚本模块)——这一点在模块 6 中很关键。

模块 0 · 准备:故障场景脚本

把 OpsKit 从 v0.2 升级到 v0.3 的目录结构,创建各模块用来故意制造错误的小脚本,并认识 $env:OPSKIT_HOME 开关:它让测试在一次性副本上运行,而不是动你真实的备份
课前 ≈ 10 分钟本机运行 · 免费只删除 ~/pslab 内的内容
前置条件
  • 第 1–4 课:由 New-LabData.ps1 生成的 ~/pslab/data,以及 v0.2 脚本模块形式的 ~/pslab/OpsKit(OpsKit.psd1、OpsKit.psm1、Public/、Private/)。
  • PowerShell 7.4 或更高版本(推荐 7.6)。有一个原生命令示例用到 git,任意已安装版本均可。
  • 有两个示例仅限 Windows(cmd /c、robocopy);文中给出 Linux/macOS 对应写法(sh -c 'exit 3'、rsync)。

热身:凭记忆回答(30 秒)

1. 在 OpsKit v0.2 中,调用者能看到哪些函数由谁决定:.psm1 还是 .psd1?

两者都会过滤:.psm1 中的 Export-ModuleMember 负责导出,清单中的 FunctionsToExport 再进一步收窄(并让自动加载能快速发现命令)。私有辅助函数对外不可见,但在模块内部可以调用。

2. 模块在 .psm1 顶部设置了 $ErrorActionPreference = 'Stop'。调用者的会话会改变吗?

不会。模块有自己的会话状态,这个变量位于模块作用域中。下面模块 6 的实验已验证:Import-Module 之后调用者的值仍是 Continue。

3. 回顾第 1 课:哪个 pwsh 开关会把脚本的 exit 3 原样传给调用者?

pwsh -File。-Command 只报告 0/1,除非你在末尾追加 ; exit $LASTEXITCODE。本课以此为基础:夜间任务好不好,全看它的退出码是否诚实。

步骤 1:OpsKit v0.3 的目录结构

v0.3 新增三个公开命令和两个私有辅助函数。清单版本升到 0.3.0;v0.2 的其余结构不变。所有新文件的完整源码见模块 8。

文件状态用途
OpsKit.psd1修改ModuleVersion = '0.3.0';FunctionsToExport 列出六个公开命令
OpsKit.psm1修改在模块作用域加入 Set-StrictMode -Version Latest 和 $ErrorActionPreference = 'Stop'(模块 5)
Public/Get-OpsConfig.ps1修改用 ThrowTerminatingError 报告 OpsKit.ConfigNotFound(模块 2)
Public/Invoke-OpsRetry.ps1新增带退避与抖动的通用重试(模块 7)
Public/Invoke-OpsBackup.ps1、Public/Remove-OpsBackup.ps1新增备份 + 轮转(模块 8)
Private/Write-OpsLog.ps1、Private/Resolve-OpsPath.ps1新增JSON 行日志;把配置中的 ~/pslab/… 映射到 OpsKit 根目录
Set-Location ~/pslab
Import-Module ./OpsKit/OpsKit.psd1 -Force
Get-Module OpsKit | Format-Table Name, Version, ModuleType -AutoSize
Get-ChildItem ./OpsKit -Recurse -File | ForEach-Object { $_.FullName.Substring($PWD.Path.Length + 1) }
Name   Version ModuleType
----   ------- ----------
OpsKit 0.3.0       Script

OpsKit\OpsKit.psd1
OpsKit\OpsKit.psm1
OpsKit\Private\Resolve-OpsPath.ps1
OpsKit\Private\Write-OpsLog.ps1
OpsKit\Public\Get-OpsConfig.ps1
OpsKit\Public\Get-OpsServer.ps1
OpsKit\Public\Invoke-OpsBackup.ps1
OpsKit\Public\Invoke-OpsRetry.ps1
OpsKit\Public\Remove-OpsBackup.ps1
OpsKit\Public\Test-OpsEndpoint.ps1

你可以边读模块 6–8 边逐步搭建 v0.3,也可以现在就把模块 8 中的所有文件粘贴进来。如果你在第 4 课从本地仓库安装过 v0.2,开发期间请按路径导入(如上),这样测试的是你正在编辑的文件,而不是已安装的副本;重新发布属于第 4 课的流程。

步骤 2:$env:OPSKIT_HOME——可以指向沙箱的根目录

配置文件里写的是 Backup.Destination = '~/pslab/backups'。从 v0.3 起,OpsKit 通过 Resolve-OpsPath 解析所有 ~/pslab/… 路径:设置了 $env:OPSKIT_HOME 就用它,否则用 ~/pslab。测试(综合实验)把它设为 ~/pslab/tmp/fi,这样故障注入可以锁定、损坏和删除文件,而不会碰到你真实的备份。生产环境保持默认即可。

$env:OPSKIT_HOME            # empty → OpsKit uses ~/pslab
# In a test only:  $env:OPSKIT_HOME = "$HOME/pslab/tmp/fi"   (child pwsh processes inherit it)

本课所有输出都是在 OpsKit 根目录指向实验目录的情况下产生的;路径统一显示为 C:\Users\labadmin\pslab\…。

步骤 3:一个能产生三种错误的脚本

保存为 ~/pslab/scripts/Show-ErrorKinds.ps1,模块 1 会运行它。

'start'
[int]'abc'          # statement-terminating: only this statement stops
'after conversion error'
Get-Item ./nope.txt # non-terminating: error written, script continues
'after Get-Item'
throw 'boom'        # script-terminating: the whole script stops
'never printed'

步骤 4:清理临时空间

New-Item -ItemType Directory -Path ~/pslab/tmp, ~/pslab/backups -Force | Out-Null
Get-ChildItem ~/pslab/tmp -File | Remove-Item -WhatIf      # look first …
Get-ChildItem ~/pslab/tmp -File | Remove-Item              # … then delete

-WhatIf 那一行是本课想培养的习惯:只要删除目标来自通配符或管道,先预览再执行。

环境自检清单

风险与清理 本课会故意锁定文件、删除旧归档、损坏一个 zip——始终只在 ~/pslab 内(综合实验只在 ~/pslab/tmp/fi 内)。实验时永远不要把 -Destination 或 $env:OPSKIT_HOME 指向你在意的目录。Remove-OpsBackup 只匹配 pslab-data-*.zip。课程结束后清理:Remove-Item ~/pslab/backups, ~/pslab/tmp/fi -Recurse -Force(第 6–8 课不需要这些归档)。

模块 1 · 错误模型:终止与非终止错误、$Error 与 ErrorRecord

00:00 – 06:00 · 每个 PowerShell 错误都是一个 ErrorRecord 对象;接下来会发生什么取决于它的类型——继续、停止当前语句,还是一路停止到最近的 try/catch——以及调用者通过 -ErrorAction 提出的要求
6 分钟$Error · Get-Error★★★★★
学习目标
  • 说出三种错误——非终止、语句终止、脚本终止——并预测每种错误之后哪些行还会执行(核心动画)。
  • 读懂 ErrorRecord 的组成:Exception、CategoryInfo、FullyQualifiedErrorId、TargetObject、InvocationInfo、ScriptStackTrace。
  • 使用 $Error、$? 和 Get-Error,并知道只有 -ErrorAction Ignore 能让错误不进入 $Error。
  • 与 Bash 对比:这里没有单一的“退出状态”,而是对象、错误类型和首选项。
前置:模块 0。重要程度:★★★★★(后面每个模块、每一起“显示成功其实失败”的事故都要回到这个模型)

What:三种错误

类型典型来源停止什么能被 try/catch 捕获吗?
非终止错误大多数 cmdlet 在某个输入项失败时:Get-Item a, missing, b、对被锁文件执行 Remove-Item;Write-Error什么都不停——错误写入第 2 流和 $Error,命令继续处理下一项,脚本继续不能,除非用 -ErrorAction Stop 或 $ErrorActionPreference = 'Stop' 提升
语句终止错误表达式中的 .NET 异常([int]'abc'、1/$zero、方法调用)、参数绑定错误、找不到命令、$PSCmdlet.ThrowTerminatingError()当前语句(管道)。下一条语句照常执行能
脚本终止错误throw;任何被 -ErrorAction Stop / $ErrorActionPreference = 'Stop' 提升的错误;解析错误沿调用栈向上的一切——函数、脚本、整条命令行——直到遇到 try/catch 或 trap能

Why:错误是对象,不是一个数字

Bash 每条命令只有一个整数,用 set -e 来响应它。PowerShell 命令一次处理很多对象,一个坏项(一千个文件里缺了一个)不应拖垮另外 999 个——所以默认是非终止错误。代价是:除非你另行要求,脚本会在出错后若无其事地继续。每个错误都是一个 System.Management.Automation.ErrorRecord:

属性告诉你什么示例(文件不存在)
Exception.NET 异常:类型、消息、内部异常、堆栈ItemNotFoundException
CategoryInfo类别(ObjectNotFound、InvalidArgument、PermissionDenied …)、目标、活动、原因ObjectNotFound: (…nope.txt:String) [Get-Item], ItemNotFoundException
FullyQualifiedErrorId稳定的标识 ErrorId,命令类型——应该用它来匹配,而不是消息(消息会被本地化)PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
TargetObject失败的那个输入项路径
InvocationInfo哪个命令、脚本、行与位置MyCommand = Get-Item
ScriptStackTracePowerShell 调用栈(函数与脚本)at Get-Thing … at Invoke-Outer …

How:$Error、$? 与 Get-Error

  • $Error 是会话中最近错误组成的 ArrayList,最新的在前($Error[0]),上限由 $MaximumErrorCount(256)决定。它是全局的:函数和模块也往同一个列表里添加。$Error.Clear() 清空。
  • 如果上一条语句写出了任何错误(包括非终止错误),$? 为 $false——但只反映上一条语句。
  • Get-Error(7.x)展开显示最新的错误(或 -Newest N)的所有嵌套属性;$ErrorView = 'DetailedView' 在显示上效果类似。
  • -ErrorAction SilentlyContinue 隐藏消息但仍会记录到 $Error;-ErrorAction Ignore 什么都不记录(下文已验证)。

When:我会得到哪一种?

问自己:“是某个 cmdlet 报告了一个输入项的问题,还是引擎无法执行一条语句?”输入项的问题是非终止错误;引擎/表达式失败是语句终止错误;throw 以及任何带 Stop 的情况是脚本终止错误。拿不准时就试一试:把这一行放进 try,看 catch 是否执行。

常见误解① “try 能捕获所有错误”——非终止错误不行(模块 2)。② “出错就说明脚本停了”——非终止和语句终止错误之后,下一行照常执行。③ “$? 能告诉我脚本是否失败”——它只反映最后一条语句。④ “SilentlyContinue 不留痕迹”——错误仍在 $Error 中。⑤ “按消息文本匹配”——消息会被本地化且会变化;应匹配 FullyQualifiedErrorId 或异常类型。⑥ “函数里的 throw 只会结束这个函数”——它会让每个调用者都停止,直到最近的 try。

图解:ErrorRecord 的结构

ErrorRecord($Error[0],catch 中的 $_)System.Management.Automation.ErrorRecord Exception.GetType() → catch [Type].Message · .InnerException CategoryInfo类别:ObjectNotFoundActivity · Reason · TargetName FullyQualifiedErrorIdPathNotFound,…GetItemCommand稳定 · 用它来匹配 TargetObject失败的输入项(路径、服务器…) InvocationInfoMyCommand · ScriptName · ScriptLineNumberPositionMessage(~~~ 下划线) ScriptStackTraceat Get-Thing … at Invoke-Outer …在你的代码中的位置
图 5-1:日志里记录 FullyQualifiedErrorId、异常类型和 TargetObject;按 id 或类型分支;把消息留给人看

流程图:一个错误会经历什么

产生错误 非终止错误(Write-Error)?先看 -ErrorAction,否则看 $ErrorActionPreference Continue / Silently / Ignore 记入 $Error(Ignore 除外)在第 2 流显示(Continue)命令和脚本继续 Stop 被提升:脚本终止(ActionPreferenceStop) 终止错误 语句终止还是脚本终止? 沿调用栈向上:有外层 try/catch 或 trap 吗?语句终止且无处理程序:只停止这条语句 执行 catch,然后继续 try 之后 无处理程序:脚本结束(exit 1)
图 5-2:首选项只对非终止错误起决定作用;终止错误会沿调用栈寻找处理程序

核心动画:一个错误会经历什么

选择一个错误并逐步观察:它的类型、是否受首选项影响、是否进入 $Error 和第 2 流、try/catch 能否看到它,以及接下来执行什么。每个场景的日志文本都是本课在 7.6.10 上的真实输出。

就绪。
动画对应的真实机制 cmdlet 用 WriteError() 报告非终止错误;引擎检查生效的 ErrorActionPreference(-ErrorAction 参数会为该命令设置一个局部的 $ErrorActionPreference),若为 Stop,就抛出携带原始记录的 ActionPreferenceStopException。终止错误是 .NET 异常(RuntimeException 等),会展开调用栈直到引擎找到 catch 或 trap;若找不到,语句终止错误只结束它所在的语句,而脚本终止错误(throw、Stop)会结束整个脚本或整条命令行。除非开启模块 3 的首选项,原生程序的退出码永远不会产生错误。

命令表

命令 / 变量用途说明
$Error[0]最新的错误全局列表,最新在前;$Error.Count、$Error.Clear()
$?上一条语句是否成功?该语句中出现任何错误(含非终止错误)即为 $false
Get-Error [-Newest N]完整展开一个错误仅 7.x;也可管道输入:$e | Get-Error
$ErrorView错误的显示方式ConciseView(默认)、NormalView、DetailedView
$e.Exception.GetType().FullName用于 catch [Type] 的异常类型也要看 .InnerException
$e.FullyQualifiedErrorId稳定标识自动化中按它分支
$e.ScriptStackTrace在你的脚本中的位置对意外错误记录它
$MaximumErrorCount$Error 的容量默认 256
$Error.Clear()
Get-Item ./data/nope.txt
$Error.Count
$e = $Error[0]
$e.GetType().FullName
$e.Exception.GetType().FullName
$e.CategoryInfo.ToString()
$e.FullyQualifiedErrorId
$e.TargetObject
$e.InvocationInfo.MyCommand.Name
Get-Item: Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist.
1
System.Management.Automation.ErrorRecord
System.Management.Automation.ItemNotFoundException
ObjectNotFound: (C:\Users\labadmin\pslab\data\nope.txt:String) [Get-Item], ItemNotFoundException
PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
C:\Users\labadmin\pslab\data\nope.txt
Get-Item

如何验证:标识分两部分:PathNotFound(cmdlet 作者选定的错误 id)和命令的类名。常见错误:在脚本里用 if ($Error) 判断失败——$Error 还包含先前命令和模块的错误;应该用 $?、-ErrorVariable 或 try/catch。生产用法:把 FullyQualifiedErrorId、异常类型和 TargetObject 作为独立字段写进日志(模块 7)。

ScriptStackTrace:谁调用了谁

function Get-Thing { [CmdletBinding()] param() Get-Item ./data/nope.txt -ErrorAction Stop }
function Invoke-Outer { Get-Thing }
try { Invoke-Outer } catch { $_.ScriptStackTrace }
at Get-Thing, <No file>: line 1
at Invoke-Outer, <No file>: line 1
at <ScriptBlock>, <No file>: line 1

SilentlyContinue 与 Ignore

$Error.Clear()
Get-Item ./data/nope.txt -ErrorAction SilentlyContinue; $?
$Error.Count
Get-Item ./data/nope.txt -ErrorAction Ignore; $?
$Error.Count
False
1
False
1

两者都让 $? 为 False;只有 SilentlyContinue 新增了一条记录(使用 Ignore 后计数仍为 1)。Ignore 不能作为 $ErrorActionPreference 的值,只能作为 -ErrorAction 的参数值。

Get-Error(节选)

Get-Item ./data/nope.txt -ErrorAction SilentlyContinue
Get-Error -Newest 1
Exception             :
    Type                 : System.Management.Automation.ItemNotFoundException
    ErrorRecord          :
        …
    ItemName             : C:\Users\labadmin\pslab\data\nope.txt
    SessionStateCategory : Drive
    TargetSite           :
        Name          : ExpandMshGlobPath
        DeclaringType : [System.Management.Automation.LocationGlobber]
        …
    Message              : Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist.
    Source               : System.Management.Automation
    HResult              : -2146233087
    StackTrace           :
   at System.Management.Automation.LocationGlobber.ExpandMshGlobPath(…)
   …
   at Microsoft.PowerShell.Commands.GetItemCommand.ProcessRecord()
TargetObject          : C:\Users\labadmin\pslab\data\nope.txt
CategoryInfo          : ObjectNotFound: (C:\Users\labadmin\pslab\data\nope.txt:String) [Get-Item], ItemNotFoundException
FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
InvocationInfo        :
    MyCommand        : Get-Item
    ScriptLineNumber : 1
    OffsetInLine     : 1
    HistoryId        : 1
    Line             : Get-Item ./data/nope.txt -ErrorAction SilentlyContinue
    …
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1

目标:在一个脚本里看到三种错误,并证明哪些行会执行。环境:~/pslab,PowerShell 7.6。成本:无;不修改磁盘内容。

在子进程中运行错误类型脚本(脚本来自模块 0):
Set-Location ~/pslab
pwsh -NoProfile -File ./scripts/Show-ErrorKinds.ps1; "exit=$LASTEXITCODE"
start
InvalidArgument: C:\Users\labadmin\pslab\scripts\Show-ErrorKinds.ps1:2
Line |
   2 |  [int]'abc'          # statement-terminating: only this statement stop …
     |  ~~~~~~~~~~
     | Cannot convert value "abc" to type "System.Int32". Error: "The input string 'abc' was not in a correct format."
after conversion error
Get-Item: C:\Users\labadmin\pslab\scripts\Show-ErrorKinds.ps1:4
Line |
   4 |  Get-Item ./nope.txt # non-terminating: error written, script continue …
     |  ~~~~~~~~~~~~~~~~~~~
     | Cannot find path 'C:\Users\labadmin\pslab\nope.txt' because it does not exist.
after Get-Item
Exception: C:\Users\labadmin\pslab\scripts\Show-ErrorKinds.ps1:6
Line |
   6 |  throw 'boom'        # script-terminating: the whole script stops
     |  ~~~~~~~~~~~~
     | boom
exit=1

“after conversion error” 和 “after Get-Item” 都输出了;“never printed” 没有输出。pwsh -File 把未处理的 throw 变成了退出码 1。注意 ConciseView 的写法:表达式错误显示类别(InvalidArgument:),cmdlet 错误显示命令名(Get-Item:)。

在当前进程中调用,并在同一行后面跟一条语句:
& ./scripts/Show-ErrorKinds.ps1; 'same line, after the script'

7.6.10 上的结果:同样的三个错误,而 'same line, after the script' 不会输出——脚本终止错误会结束整条命令行(或整个调用脚本),而不只是被调用的脚本。在新的提示符下输入下一条命令则会正常执行。

解剖最后一个错误:运行“命令”分页中的代码块(从 $Error.Clear() 到 MyCommand.Name),记下 FullyQualifiedErrorId。然后对 [int]'abc' 做同样的事:
[int]'abc'
$Error[0].FullyQualifiedErrorId; $Error[0].Exception.GetType().Name; $Error[0].CategoryInfo.Category
InvalidArgument: Cannot convert value "abc" to type "System.Int32". Error: "The input string 'abc' was not in a correct format."
InvalidCastFromStringToInteger
RuntimeException
InvalidArgument

异常类型是笼统的 RuntimeException;具体信息在 id InvalidCastFromStringToInteger 中——这是应按 id 匹配的又一个理由。

清理:$Error.Clear()(磁盘上没有需要删除的内容)。

案例 1:“任务是绿的,但一半文件根本没复制”

问题:一个同步脚本每晚执行 Copy-Item $files -Destination \\nas\share,连续几周都报告成功;审计发现少了 200 个文件。根因:被其他进程锁定的文件产生了非终止错误;脚本继续执行并以 exit 0 结束。没人去看调度器输出里的红字。修复:让边界严格——$ErrorActionPreference = 'Stop' 加上对每个文件的 try/catch,统计失败数,有失败就以非零码退出;为每个失败记录 TargetObject(模块 7)。

案例 2:按英文错误文本设置的告警

问题:监控规则匹配日志中的 "Cannot find path";在德语界面的服务器上从未触发。根因:异常消息会被本地化。修复:记录并匹配 FullyQualifiedErrorId(PathNotFound,…)和异常类型——两者都与语言区域无关。

案例 3:“我们检查了 $Error,结果部署每次都失败”

问题:部署脚本最后写着 if ($Error.Count -gt 0) { exit 1 },在构建代理上每次都失败。根因:开头导入的某个模块向全局 $Error 写入了一个无害、已被吞掉的错误。修复:永远不要把 $Error 当作成功信号;用 -ErrorVariable 或 try/catch 捕获你真正关心的命令的错误。

常见错误与解决

出现了红字,但我的 catch 块从不执行

原因:这是非终止错误。

try { Get-Item ./data/nope.txt -ErrorAction Stop } catch { "caught: $($_.FullyQualifiedErrorId)" }

解决:给命令加 -ErrorAction Stop,或在脚本边界设置 $ErrorActionPreference = 'Stop'(模块 2)。

出错后脚本继续执行,还打印了 “done”

原因:没有处理程序的非终止或语句终止错误。解决:对每个步骤明确决定失败时是否必须停止;如果必须,就用 Stop + try/catch,并以非零码退出。

我看不出模块里是哪一行失败了
$Error[0].ScriptStackTrace
$Error[0].InvocationInfo.PositionMessage
Get-Error -Newest 1

解决:对意外错误记录 ScriptStackTrace;ConciseView 只显示最外层的位置。

$Error 里全是旧错误,找不到我的那个

解决:实验前执行 $Error.Clear(),或用 -ErrorVariable myErr 只捕获该命令的错误。

命令行练习
1. 按从新到旧的顺序,打印当前 $Error 中每个错误的 id 和失败目标。
$Error | ForEach-Object { '{0} -> {1}' -f $_.FullyQualifiedErrorId, $_.TargetObject }
2. 证明 Get-Item a, missing, b 仍然返回两个项。
$r = Get-Item ./data/servers.csv, ./data/nope.txt, ./data/access.log
$r.Name
Get-Item: Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist.
servers.csv
access.log
场景分析
同事的清理脚本执行 Get-ChildItem $logDir | Remove-Item,然后向状态文件写入 “cleanup complete”。部分日志被 Web 服务器锁定。状态文件里写的是什么?磁盘上是什么情况?你会怎么改?

状态文件写着 “cleanup complete”——Remove-Item 为每个被锁文件写了一个非终止错误后继续,下一条语句照常执行。磁盘上被锁的文件还在。修改:用 -ErrorVariable rmErr(或 Stop + 逐文件 try/catch)收集错误,写入包含 $rmErr.Count 和 TargetObject 列表的状态,计数大于零时以非零码退出(或稍后重试,模块 7)。并明确决定:被锁的日志算失败,还是预期内的跳过。

经核实的教学视频

▶
PowerShell Quick Tips : Errors — JackedProgrammer
英文 · 几分钟讲清终止与非终止错误
▶
PowerShell Errors and Exceptions Handling — TechThoughts
英文 · 错误记录、$Error、终止与非终止错误

官方文档

视频分镜(约 90 秒)

本资料无法直接生成视频或 MP3;分镜与讲解稿可交给视频工具使用。

镜头 1 · 0–20 秒
画面:三个文件流入 Get-Item;中间那个变红,另外两个照样输出。
讲解:非终止错误报告一个坏项,然后继续。
镜头 2 · 20–45 秒
画面:一段脚本;一条红条划过一行([int]'abc'),下一行亮起;随后是 throw 那一行,其余所有行变灰。
讲解:语句终止只停一条语句;脚本终止会停掉一切,直到最近的 catch。
镜头 3 · 45–70 秒
画面:一个 ErrorRecord 展开成六张带标签的卡片(Exception、CategoryInfo、FullyQualifiedErrorId …)。
讲解:错误是对象。按 id 匹配,不要按消息。
镜头 4 · 70–90 秒
画面:调度器上绿色的“成功”标记,然后放大镜照出日志里的红字。
讲解:不让脚本停止的错误,才是在生产中伤害你的错误。
或测验得分 ≥ 70%

模块 2 · -ErrorAction、try / catch / finally、按类型捕获、throw 与 Write-Error

06:00 – 13:00 · try/catch 只能看到终止错误;-ErrorAction Stop 和 $ErrorActionPreference 会提升其余错误;按类型的 catch 块根据 .NET 类型挑选;你自己的函数决定以多大“音量”失败
7 分钟try · catch · finally · trap★★★★★
学习目标
  • 解释为什么 try { Get-Item missing } 走不到 catch,并用两种方式修复(-ErrorAction Stop、$ErrorActionPreference)。
  • 编写有序的、按类型的 catch 块,以及一定会执行的 finally。
  • 在高级函数中选择 throw(脚本终止)、Write-Error(非终止)或 $PSCmdlet.ThrowTerminatingError()(语句终止)。
  • 使用 -ErrorVariable(加 +name 表示追加),并能认出旧代码中的 trap。
前置:模块 1。重要程度:★★★★★

What:ErrorAction 的取值

取值显示错误?加入 $Error?继续?典型用途
Continue(默认)是是是交互式操作
SilentlyContinue否是是“找不到也没关系”,如 Get-Command x -ErrorAction SilentlyContinue
Ignore否否是同上,但不污染 $Error;只能作为参数值
Stop经由 catch是否——脚本终止try 内的一切;脚本边界
Inquire询问是由用户决定仅用于调试;在 -NonInteractive 下会失败
Break进入调试器是—调试(7.x)

-ErrorAction(每个 cmdlet 和高级函数都有的通用参数)对单个命令覆盖 $ErrorActionPreference。两者都不影响不是由命令产生的语句终止错误(参数绑定错误、.NET 异常)——但有一个怪癖:$ErrorActionPreference = 'SilentlyContinue' 也会隐藏语句终止错误(下文已验证)。永远不要在全局这样设置。

Why:try 只能看到终止错误

非终止错误只是写到第 2 流的一条记录,并没有可以捕获的异常。-ErrorAction Stop 在源头把它变成异常,catch 块收到的是原始的 ErrorRecord,所以按类型捕获仍然有效:即使引擎在途中把它包装成了 ActionPreferenceStopException,catch [System.Management.Automation.ItemNotFoundException] 仍能捕获文件不存在的错误。

How:在你自己的函数中报告错误

写法对调用者而言的类型调用者的下一条语句(无 try)适用场景
Write-Error 'msg' / $PSCmdlet.WriteError($rec)非终止执行;你的函数也继续运行某个输入项失败,其他项可能成功
$PSCmdlet.ThrowTerminatingError($rec)语句终止执行(即使在同一行)你的命令完全无法完成工作(缺少配置)。高级函数中的最佳实践:错误看起来来自你的命令,而不是来自命令内部的某一行
throw 'msg' / throw $rec脚本终止不执行——除非被捕获,否则整个脚本停止脚本和内部代码;在后续操作会造成危险时

三者都已在 7.6.10 的“命令”分页中验证。后两者的差别让大多数人意外:使用 ThrowTerminatingError 的模块(cmdlet 也是如此)本身并不会让调用者的脚本停止——调用者必须使用 -ErrorAction Stop、$ErrorActionPreference = 'Stop' 或 try/catch。这正是模块 8 “脚本报告成功”排错树的根源。

When:catch 的顺序、finally、trap

  • catch 块从上到下依次测试;第一个类型匹配(含基类型)的胜出。具体类型放前面,不带类型的 catch 放最后。
  • finally 在 try(及 catch)之后执行,无论是否出错——即使 catch 重新抛出或用户按下 Ctrl+C。用它关闭文件、恢复位置、释放句柄。
  • trap 是 v2 之前的机制:整个作用域的处理程序;continue 从出错语句之后继续,break 重新抛出。你会在旧脚本里见到它;新代码请用 try/catch。
  • 在 catch 中,$_(或 $PSItem)就是 ErrorRecord;单独一个 throw 会原样重新抛出它。
常见误解① “不加 -ErrorAction Stop,catch 也能捕获 cmdlet 的错误”——只对本来就是终止错误的有效。② “我的脚本里设了 Stop 就够了,所以模块不需要自己的错误策略”——模块无法知道调用者如何设置首选项;它应该明确决定(OpsKit 在模块作用域设置 Stop,并用稳定的 id 报告错误)。③ “函数里的 throw 只是返回一个错误”——它会停止每个调用者。④ “把 catch [Exception] 放第一个没问题”——它会吞掉下面所有的情况。⑤ “Get-Item -Nope 加上 -ErrorAction SilentlyContinue 会隐藏错误”——参数绑定错误不受影响(已验证)。

图解:try / catch / finally 的控制流

try { … -ErrorAction Stop }第一个终止错误立即跳出 错误 catch [ItemNotFoundException] catch [System.ArgumentException] catch { } —— 其他一切 从上到下测试;第一个匹配者胜出(基类型也会匹配) finally { }总会执行:成功、catch、重新抛出、Ctrl+C 无错误 try 之后的语句(除非重新抛出) 没有 catch 匹配?先执行 finally,然后错误继续向外层 try 展开
图 5-3:finally 用于清理;catch 用于决策

图解:高级函数报告失败的三种方式

Write-Error非终止函数继续调用者继续调用者的 -ErrorAction Stop会提升它 ThrowTerminatingError语句终止函数停止调用者的下一条语句执行错误显示你的命令名和你的错误 id throw脚本终止函数停止每个调用者都停止直到 try/catch 或 trap(pwsh -File:exit 1)
图 5-4:已在 7.6.10 验证——Test-TTE; 'next' 会输出 'next',Test-Throw; 'next' 不会

哪个 catch 块会执行?

函数 Read-Config(见“命令”分页)在带三个 catch 块和一个 finally 的 try 中读取 JSON 文件。选择一个输入,观察由哪个块处理。

就绪。
动画对应的真实机制 当终止错误离开 try 块时,PowerShell 按源码顺序遍历各个 catch 子句,对其中列出的每个类型测试 $exception -is [Type](一个子句可以用逗号列出多个类型)。对于由 Stop 提升的错误,测试针对的是 ErrorRecord 中的原始异常,所以 ItemNotFoundException 能匹配。finally 被编译成 .NET 的 finally 块,因此在每一条退出路径上都会执行。

命令表

语法用途说明
-ErrorAction Stop / -EA Stop提升该命令的错误try 的常用搭档
$ErrorActionPreference = 'Stop'提升当前作用域中所有命令的错误放在脚本顶部,而不是配置文件中
catch [T1], [T2] { }按类型捕获使用 .NET 完整类型名;具体的放前面
finally { }清理每条路径都执行
throw(在 catch 中)重新抛出当前错误保留原始 ErrorRecord
$PSCmdlet.ThrowTerminatingError($rec)让高级函数失败对调用者是语句终止
-ErrorVariable ev / +ev捕获该命令的错误变量名不带 $;+ 表示追加
trap [T] { …; continue }作用域级处理程序(旧式)优先使用 try/catch
try { Get-Item ./data/nope.txt; 'try block finished' } catch { "caught: $_" }
try { Get-Item ./data/nope.txt -ErrorAction Stop; 'not reached' } catch { "caught: $($_.Exception.GetType().Name)" }
Get-Item: Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist.
try block finished
caught: ItemNotFoundException

如何验证:第一个 try “finished”了——catch 从未执行。常见错误:以为出现红字就说明 catch 处理过了。生产用法:凡是失败后需要改变控制流的命令,都加 -ErrorAction Stop,或在脚本顶部设置首选项。

按类型的 catch 块与 finally

function Read-Config([string]$Path) {
    try {
        $raw = Get-Content -LiteralPath $Path -Raw -ErrorAction Stop
        $raw | ConvertFrom-Json -ErrorAction Stop
    }
    catch [System.Management.Automation.ItemNotFoundException] {
        "missing file: $Path"
    }
    catch [System.ArgumentException] {
        "bad JSON ($($_.Exception.GetType().Name))"
    }
    catch {
        "other: $($_.Exception.GetType().FullName)"
    }
    finally {
        "finally ran for $Path"
    }
}
Read-Config ./data/nope.json
Read-Config ./data/servers.csv
missing file: ./data/nope.json
finally ran for ./data/nope.json
bad JSON (ArgumentException)
finally ran for ./data/servers.csv

在 7.6.10 上,ConvertFrom-Json 把无效输入报告为 System.ArgumentException——在写类型化 catch 之前,先在不带类型的 catch 中用 $_.Exception.GetType().FullName 查看你所用版本上的实际类型。注意 finally 的输出也是函数输出的一部分:在返回数据的函数里,可以在 finally 中清理,但不要从中输出值。

首选项变量

$ErrorActionPreference = 'Stop'
try { Get-Item ./data/nope.txt; 'not reached' } catch { "caught with preference: $($_.FullyQualifiedErrorId)" }
$ErrorActionPreference = 'Continue'
caught with preference: PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand

Write-Error、ThrowTerminatingError 与 throw(在脚本中)

function Test-WError { [CmdletBinding()] param() Write-Error 'written'; 'Test-WError kept going' }
function Test-TTE    { [CmdletBinding()] param()
    $err = [System.Management.Automation.ErrorRecord]::new(
        [System.IO.FileNotFoundException]::new('config missing'), 'OpsKit.ConfigMissing',
        [System.Management.Automation.ErrorCategory]::ObjectNotFound, './opskit.config.psd1')
    $PSCmdlet.ThrowTerminatingError($err)
    'not reached'
}
Test-WError; 'caller after Test-WError'
Test-TTE; 'caller after Test-TTE (same line)'
'next line after Test-TTE'
Test-WError -ErrorAction Stop; 'caller after Test-WError -EA Stop'
'next line'
Test-WError: written
Test-WError kept going
caller after Test-WError
Test-TTE: config missing
caller after Test-TTE (same line)
next line after Test-TTE
Test-WError: written

调用者的 -ErrorAction Stop 把非终止的 Write-Error 变成了脚本终止错误:“caller after …”和 “next line” 都没有执行,脚本以 1 退出。对于 function Test-Throw { [CmdletBinding()] param() throw 'thrown' },Test-Throw; 'caller after' 只输出了 Exception: thrown,退出码为 1。

按类型和按 id 捕获

try { Test-Nothing } catch { $_.Exception.GetType().Name }
try { Test-TTE } catch { "$($_.FullyQualifiedErrorId) | $($_.CategoryInfo.Category) | $($_.Exception.GetType().Name)" }
try { throw [System.TimeoutException]::new('slow') } catch [System.TimeoutException] { "typed: $($_.Exception.Message)" }
CommandNotFoundException
OpsKit.ConfigMissing,Test-TTE | ObjectNotFound | FileNotFoundException
typed: slow

-ErrorVariable 与 trap

Get-Item ./data/servers.csv, ./data/nope1, ./data/nope2 -ErrorAction SilentlyContinue -ErrorVariable ev |
    Select-Object -ExpandProperty Name
$ev.Count
$ev | ForEach-Object { $_.TargetObject | Split-Path -Leaf }
Get-Item ./data/nope3 -ErrorAction SilentlyContinue -ErrorVariable +ev
$ev.Count

function Invoke-WithTrap {
    trap [System.DivideByZeroException] { "trap: $($_.Exception.Message)"; continue }
    'before'
    $z = 0; 1 / $z
    'after (trap used continue)'
}
Invoke-WithTrap
servers.csv
2
nope1
nope2
3
before
trap: Attempted to divide by zero.
after (trap used continue)

两个值得了解的怪癖

Get-Item ./data -Nope -ErrorAction SilentlyContinue; "binding error not suppressed: ?=$?"
$ErrorActionPreference = 'SilentlyContinue'
[int]'abc'; "conversion error hidden by the preference variable, ?=$?"
$ErrorActionPreference = 'Continue'
Get-Item: A parameter cannot be found that matches parameter name 'Nope'.
binding error not suppressed: ?=False
conversion error hidden by the preference variable, ?=False

目标:让配置读取函数对每种错误输入都以正确方式失败。环境:~/pslab。成本:无。

粘贴“命令”分页中的 Read-Config,用三种输入调用它(不存在、CSV、有效 JSON)。确认每次调用都出现 “finally ran”。
去掉 Get-Content 那一行的 -ErrorAction Stop,再次调用 Read-Config ./data/nope.json。先预测再检查:出现红色的 Get-Content 错误,$raw 为 $null,ConvertFrom-Json 什么也没收到——函数只返回 “finally ran …”。这种悄无声息的空结果比报错更糟。
升级为能正确失败的高级函数:
function Read-OpsJson {
    [CmdletBinding()]
    param([Parameter(Mandatory)][string]$Path)
    try {
        Get-Content -LiteralPath $Path -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
    }
    catch {
        $PSCmdlet.ThrowTerminatingError($_)     # re-raise as OUR error, statement-terminating
    }
}
try { Read-OpsJson ./data/servers.csv } catch { "caller saw: $($_.FullyQualifiedErrorId)" }

传入 $_ 会保留原始 id 和异常;调用者看到的错误来自 Read-OpsJson。7.6.10 上的实际结果:caller saw: System.ArgumentException,Read-OpsJson。

收集错误而不中断:读取三个文件,出错继续,最后汇总:
$ok = Get-Item ./data/servers.csv, ./data/nope1, ./data/nope2 -ErrorAction SilentlyContinue -ErrorVariable ev
"{0} ok, {1} failed: {2}" -f @($ok).Count, $ev.Count, (($ev.TargetObject | Split-Path -Leaf) -join ', ')
清理:Remove-Item Function:Read-Config, Function:Read-OpsJson -ErrorAction Ignore

案例 1:掩盖了权限问题的“万能 catch”

问题:一个资源配置脚本把所有代码包在 try { … } catch { Write-Host 'retrying later' } 中。整整一周它都在“稍后重试”。根因:catch 对 UnauthorizedAccessException(永久性错误)和瞬时网络抖动一视同仁。修复:按类型捕获——瞬时类型(IOException、TimeoutException、HttpRequestException)走重试路径(模块 7);其余记录日志后用 throw 重新抛出。

案例 2:从未发生的清理

问题:脚本用 New-PSDrive 挂载共享,完成工作后在末尾移除驱动器。失败几次之后,残留的驱动器越积越多。根因:移除语句写在工作代码之后,任何终止错误都会跳过它。修复:把清理移到 finally:try { New-PSDrive …; work } finally { Remove-PSDrive X -ErrorAction Ignore }。

案例 3:“有时会”中断管道的模块函数

问题:内部函数 Get-Tenant 的调用者反映,缺一个租户就会让整份报表失败。根因:函数对“找不到”使用了 throw。修复:单个项的问题用 Write-Error(通过 $PSCmdlet.WriteError() 带上合适的 id),整个命令的失败用 ThrowTerminatingError;想要停止的调用者自己加 -ErrorAction Stop。

常见错误与解决

Unable to find type [ItemNotFoundException]

原因:catch 中的类型需要完整名称,除非用 using namespace 导入了命名空间。

catch [System.Management.Automation.ItemNotFoundException] { }
# or at the top of the script:
using namespace System.Management.Automation
类型化的 catch 从未命中,命中的总是不带类型的 catch

原因:实际异常类型不同(常见的是包装器:MethodInvocationException 包着 IOException)。

catch { $_.Exception.GetType().FullName; $_.Exception.InnerException.GetType().FullName }

解决:捕获包装器类型,或在不带类型的 catch 中检查 InnerException(OpsKit 的 Invoke-OpsRetry 会遍历异常链)。

设置 Stop 之后,脚本在一个无害的 Get-Command 检查处停止了

解决:局部放行:Get-Command az -ErrorAction Ignore。全局 Stop 加局部例外才是正确的默认做法。

finally 的文本混进了函数的返回值

解决:不要从 finally 输出内容;需要提示时用 Write-Verbose。

命令行练习
1. 读取 ./data/opskit.config.psd1;文件不存在时输出 “no config”,其他错误重新抛出。
try { Import-PowerShellDataFile -LiteralPath ./data/opskit.config.psd1 -ErrorAction Stop }
catch [System.Management.Automation.ItemNotFoundException] { 'no config' }
catch { throw }
2. 对三个路径执行 Get-Item,只输出失败项的名称。
$null = Get-Item ./data/a, ./data/servers.csv, ./data/b -ErrorAction SilentlyContinue -ErrorVariable bad
$bad.TargetObject | Split-Path -Leaf
场景分析
团队模块函数 Set-OpsDns 在 DNS 服务器不可达时失败,目前用的是 throw。一个调用者在 foreach 中为 40 条记录调用它,抱怨一条坏记录导致其余 39 条也没执行。另一个调用者则希望第一次失败就停止整个运行。如何同时满足两者?

把单条记录遇到服务器不可达视为单项失败:用 $PSCmdlet.WriteError() 报告(非终止、稳定 id、TargetObject 设为该记录)并继续。第一个调用者得到 39 个成功和 -ErrorVariable 中的一个错误;第二个调用者加上 -ErrorAction Stop(或设置首选项),第一个错误就会被提升为脚本终止。如果服务器对所有记录都不可达(在 begin 中检测一次),就用 ThrowTerminatingError。throw 留给内部缺陷。

经核实的教学视频

▶
PowerShell 7 Tutorials for Beginners #10 : Error Handling (Try Catch Finally) — JackedProgrammer
英文 · PowerShell 7 中的 try/catch/finally
▶
How to Handle Errors in PowerShell | Try, Catch, and Finally — Cloud360 Training
英文 · try、catch 与 finally 基础
▶
Error Handling in PowerShell — PDQ
英文 · 错误处理直播讲解

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:try 框里放着 Get-Item;红字从 catch 框旁边飞过,catch 框始终是暗的。
讲解:try 只能看到终止错误。
镜头 2 · 20–40 秒
画面:“-ErrorAction Stop” 卡到命令上;这次错误落进了 catch。
讲解:在源头提升,catch 收到的是原始错误。
镜头 3 · 40–65 秒
画面:三个 catch 框叠在一起;错误逐个往下掉,直到匹配;底部的 finally 条在每条路径上都亮起。
讲解:具体类型在前,不带类型的 catch 在后,清理放进 finally。
镜头 4 · 65–90 秒
画面:三个函数图标 Write-Error、ThrowTerminatingError、throw,分别亮起绿、黄、红三色的“调用者继续吗?”指示灯。
讲解:决定你的函数以多大音量失败。
或测验得分 ≥ 70%

模块 3 · 原生命令:$LASTEXITCODE 与 $PSNativeCommandUseErrorActionPreference

13:00 – 21:00 · git、az、robocopy 以及所有其他程序都用退出码而不是异常来报告失败;默认情况下 PowerShell 只记录下来然后继续——除非你选择把非零退出码变成错误
8 分钟7.4+ 正式功能★★★★★
学习目标
  • 在原生程序之后读取 $LASTEXITCODE 和 $?,并知道非零退出码默认不是错误(不进 $Error,不触发 catch)。
  • 用 $PSNativeCommandUseErrorActionPreference = $true + $ErrorActionPreference = 'Stop' 把退出码变成可捕获的错误,并读懂由此产生的 NativeCommandExitException。
  • 在 7.x 中正确处理 stderr:它不是失败信号;使用 2>&1 时,每一行都会变成 ErrorRecord 对象。
  • 对非零码也表示成功的程序(robocopy 1–7),在局部作用域中关闭该首选项。
前置:模块 1–2;第 1 课模块 8(退出码)。重要程度:★★★★★(“构建坏了但 CI 显示通过”最常见的原因)

What:原生程序的两个信号

信号在 PowerShell 中去向表示失败?
退出码$LASTEXITCODE(整数);非零时 $? 变为 $false按惯例是(0 = 成功)——但有些工具不同(robocopy、diff、grep 无匹配时返回 1)
stdout成功流,每行一个 [string]否
stderr直接输出到控制台;使用 2>&1 或 2> 重定向时,每行一个 ErrorRecord(类别 NotSpecified,id NativeCommandError)否。许多工具把进度写到 stderr(git、curl、terraform)。从 7.2 起,stderr 永远不会把 $? 设为 false,也不受 $ErrorActionPreference 影响

Why:默认是“记录并继续”

开箱即用时,cmd /c exit 3 或失败的 git push 会设置 $LASTEXITCODE 和 $?,不写入 $Error,下一行照常执行——即使在 try 中且 $ErrorActionPreference = 'Stop' 也一样。这和没有 set -e 的 Bash 完全相同。你要么在每次调用后检查 $LASTEXITCODE,要么启用 7.4+ 的行为:

$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true    # 7.4+: non-zero exit → NativeCommandExitException

启用后,非零退出码会产生一个错误,其严重程度跟随 $ErrorActionPreference(Stop → 脚本终止;Continue → 显示为非终止错误)。这是 PowerShell 中最接近 set -e 的东西,而且它不看 stderr。

How:三种模式

模式代码适用场景
显式检查git fetch; if ($LASTEXITCODE -ne 0) { throw "git fetch failed: $LASTEXITCODE" }在 5.1 中也可用;需要为每条命令定制消息时
全局启用$ErrorActionPreference = 'Stop'; $PSNativeCommandUseErrorActionPreference = $trueCI 脚本、包装大量原生调用的脚本
局部关闭& { $PSNativeCommandUseErrorActionPreference = $false; robocopy … }; if ($LASTEXITCODE -ge 8) { throw … }退出码不标准的工具

When:哪次调用之后检查什么

  • $LASTEXITCODE 只由原生程序和调用了 exit 的脚本设置;cmdlet 不会动它。要立刻读取——下一次原生调用会覆盖它。
  • 原生调用之后,当且仅当退出码非零时 $? 为 $false(7.2+)。
  • 重定向 stderr:2>$null 丢弃;2>&1 以 ErrorRecord 形式合并(如需纯字符串,用 | ForEach-Object { "$_" } 转换)。在 7.x 中这些被重定向的记录不会加入 $Error(已验证)。
  • 与 Bash 对比:set -e ≈ $PSNativeCommandUseErrorActionPreference = $true + Stop;set -o pipefail——由原生命令组成的 PowerShell 管道只报告最后一个命令的退出码;如果重要,就逐步检查。
常见误解① “try/catch 能捕获失败的 git 命令”——没有该首选项就不能。② “有 stderr 输出就是失败了”——git 和 curl 把进度写在那里;要看退出码。③ “7.4+ 默认开启了 $PSNativeCommandUseErrorActionPreference”——它是正式功能,但默认值是 $false(已验证)。④ “非零退出就是失败”——robocopy 在复制了文件时返回 1。⑤ “$LASTEXITCODE 能告诉我上一个 cmdlet 是否成功”——cmdlet 从不设置它。

图解:从退出码到 PowerShell 错误

原生进程git · cmd · robocopyaz · terraform stdout 成功流每行一个 [string] stderr 控制台,或使用 2>&1 时:每行一个 ErrorRecord从不设置 $?(7.2+) 退出码 $LASTEXITCODE = n$? = (n -eq 0) $PSNativeCommand…UseErrorActionPreference且 n ≠ 0 ? $true NativeCommandExitExceptionProgramExitedWithNonZeroCode严重程度 = $ErrorActionPreference $false 不会发生任何其他事
图 5-5:stderr 和退出码是两个独立的通道;只有退出码可能变成错误,而且只在你启用后

原生退出码路由

选择一次原生调用和首选项设置;跟随退出码和 stderr 穿过 PowerShell。

就绪。
动画对应的真实机制 原生进程退出时,引擎把退出码存入 $global:LASTEXITCODE 并设置 $?。如果 $PSNativeCommandUseErrorActionPreference 为 $true 且退出码非零,引擎会通过常规错误管道写出一个包装 System.Management.Automation.NativeCommandExitException(含 ExitCode、Path、ProcessId)的 ErrorRecord,于是由 $ErrorActionPreference 决定其严重程度。stderr 是异步读取的,只有被重定向时才会变成 ErrorRecord。

命令表

项目用途说明
$LASTEXITCODE上一个原生程序的退出码全局;会被下一次原生调用或 exit 覆盖
$?上一条语句是否成功对原生程序:退出码 = 0
$PSNativeCommandUseErrorActionPreference退出码 → 错误7.4+;默认 $false;像普通变量一样有作用域
2>$null丢弃 stderr不改变退出码
2>&1把 stderr 合并进输出各行变成 ErrorRecord;"$_" 取得文本
[System.Management.Automation.NativeCommandExitException]catch 类型.ExitCode、.Path
Start-Process -Wait -PassThru不捕获输出地运行返回的进程对象有 .ExitCode;很少需要
cmd /c exit 3; "LASTEXITCODE=$LASTEXITCODE  ?=$?"          # Linux/macOS: sh -c 'exit 3'
cmd /c exit 0; "LASTEXITCODE=$LASTEXITCODE  ?=$?"
try { cmd /c exit 3; 'try finished: native failure is not an exception' } catch { 'caught' }
LASTEXITCODE=3  ?=False
LASTEXITCODE=0  ?=True
try finished: native failure is not an exception

如何验证:原生调用失败后 $Error.Count 不变。常见错误:把 terraform apply 包进 try/catch,以为失败会被捕获。生产用法:CI 脚本以这两行首选项开头;必须容忍某些退出码的包装脚本在局部关闭首选项。

启用:非零退出变成异常

$PSNativeCommandUseErrorActionPreference          # default
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
try { cmd /c exit 3; 'not reached' }
catch {
    $_.Exception.GetType().FullName
    $_.Exception.Message
    "ExitCode property: $($_.Exception.ExitCode)"
    $_.FullyQualifiedErrorId
}
False
System.Management.Automation.NativeCommandExitException
Program "cmd.exe" ended with non-zero exit code: 3 (0x00000003).
ExitCode property: 3
ProgramExitedWithNonZeroCode
# Same preference, but $ErrorActionPreference left at Continue: shown, not fatal
$PSNativeCommandUseErrorActionPreference = $true
cmd /c exit 3; "Continue preference: LASTEXITCODE=$LASTEXITCODE"
NativeCommandExitException: Program "cmd.exe" ended with non-zero exit code: 3 (0x00000003).
Continue preference: LASTEXITCODE=3

stderr 不等于失败

$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
cmd /c "echo to-stderr 1>&2"; "stderr alone did not stop anything, exit=$LASTEXITCODE"
$out = cmd /c "echo line1 & echo oops 1>&2 & echo line2" 2>&1
$out | ForEach-Object { '{0,-12} {1}' -f $_.GetType().Name, $_ }
to-stderr
stderr alone did not stop anything, exit=0
String       line1
ErrorRecord  oops
String       line2
cmd /c "echo oops 1>&2" 2>$null; "?=$?  LASTEXITCODE=$LASTEXITCODE"
$r = cmd /c "echo out & echo err 1>&2" 2>&1; $r.Count; $Error.Count
?=True  LASTEXITCODE=0
2
0

git:退出码与 stderr 记录

git --no-such-option 2>$null; "git exit=$LASTEXITCODE"
git -C ./data rev-parse --is-inside-work-tree 2>&1 | ForEach-Object { "[{0}] {1}" -f $_.GetType().Name, $_ }; "git exit=$LASTEXITCODE"
git exit=129
[ErrorRecord] fatal: not a git repository (or any of the parent directories): .git
git exit=128

robocopy 陷阱与局部关闭

$PSNativeCommandUseErrorActionPreference = $true
$ErrorActionPreference = 'Stop'
robocopy ./data/files ./tmp/files-copy /E /NJH /NJS /NP /NFL /NDL; "robocopy exit=$LASTEXITCODE"
NativeCommandExitException: Program "Robocopy.exe" ended with non-zero exit code: 1 (0x00000001).
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
& { $PSNativeCommandUseErrorActionPreference = $false; robocopy ./data/files ./tmp/files-copy2 /E /NJH /NJS /NP /NFL /NDL }
if ($LASTEXITCODE -ge 8) { throw "robocopy failed: $LASTEXITCODE" }
"robocopy exit=$LASTEXITCODE (0-7 = success for robocopy)"
robocopy exit=1 (0-7 = success for robocopy)

子作用域 & { } 只在该块内关闭首选项;$LASTEXITCODE 是全局的,因此块之后的检查仍能看到 robocopy 的退出码。在 Linux 上,grep(1 = 无匹配)和 diff(1 = 文件不同)也是同样的情况。

目标:编写一个能安全运行原生工具的小包装函数。环境:~/pslab;Windows 示例用 cmd/robocopy,Linux/macOS 用 sh/rsync。成本:无;副本留在 ~/pslab/tmp。

默认行为:运行“命令”分页的第一个代码块,确认 catch 从未执行、$Error 仍为空。
启用:在一个新的 pwsh -NoProfile 中设置两个首选项,在 try 中运行 git --no-such-option,打印 $_.Exception.ExitCode(预期:129)。
一个可复用的辅助函数:
function Invoke-Native {
    [CmdletBinding()]
    param([Parameter(Mandatory)][string]$FilePath, [string[]]$ArgumentList = @(), [int[]]$SuccessCodes = 0)
    $out = & $FilePath @ArgumentList 2>&1 | ForEach-Object { "$_" }
    $code = $LASTEXITCODE
    if ($code -notin $SuccessCodes) {
        $PSCmdlet.ThrowTerminatingError([System.Management.Automation.ErrorRecord]::new(
            [System.Exception]::new("$FilePath exited with $code`n$($out -join "`n")"),
            'Native.ExitCode', 'NotSpecified', $FilePath))
    }
    $out
}
Invoke-Native git '--version'
try { Invoke-Native git '--no-such-option' } catch { $_.FullyQualifiedErrorId }
Invoke-Native robocopy './data/files', './tmp/rc', '/E', '/NJH', '/NJS', '/NP', '/NFL', '/NDL' -SuccessCodes (0..7)   # Windows

该函数把 stdout 和 stderr 一起保留为纯文本,按工具定义成功码,并抛出一个带稳定 id、消息中含工具输出的错误。7.6.10 上实测:第一行输出 git version 2.51.2.windows.1,第二行输出 Native.ExitCode,Invoke-Native,robocopy 一行没有输出也没有报错。

清理:Remove-Item ./tmp/files-copy, ./tmp/files-copy2, ./tmp/rc -Recurse -Force -ErrorAction Ignore

案例 1:什么都没部署却显示绿色的流水线

问题:GitHub Actions 的一个步骤运行 az deployment group create …,随后 Write-Host 'Deployed'。部署在验证阶段失败;步骤却是绿色。根因:az 以 1 退出,但步骤脚本的最后一条命令(Write-Host)成功了,所以步骤以 0 退出。修复:每个 pwsh CI 脚本都以 $ErrorActionPreference = 'Stop' 和 $PSNativeCommandUseErrorActionPreference = $true 开头(或在每次原生调用后检查 $LASTEXITCODE)。

案例 2:Windows PowerShell 5.1 因 git 进度输出而停止

问题:一个设置了 $ErrorActionPreference = 'Stop' 的旧 5.1 构建脚本,在 git clone … 2>&1 处中止,尽管克隆成功了。根因:在 5.1 中,被重定向的 stderr 行是受首选项影响的真正错误;而 git 把进度写到 stderr。修复:迁移到 pwsh 7.2+(stderr 不再触发 Stop),或在 5.1 中不加 2>&1 运行 git 并检查 $LASTEXITCODE。

案例 3:团队开启首选项后 robocopy“失败”了

问题:全局采用 7.4 首选项之后,所有文件同步作业都失败了——偏偏是在复制了文件的时候。根因:robocopy 的退出码是位字段:1 = 已复制文件,2 = 有多余文件,8+ = 失败(已验证:exit 1 变成了 NativeCommandExitException)。修复:局部关闭首选项加 if ($LASTEXITCODE -ge 8),或使用带 -SuccessCodes (0..7) 的辅助函数。

常见错误与解决

NativeCommandExitException: Program "X" ended with non-zero exit code

原因:首选项已开启,且工具返回了非零码。解决:判断这个退出码对该工具是否真的代表失败;若不是,就为这次调用局部关闭首选项。

$LASTEXITCODE 是 0,但工具显然失败了

原因:中间又运行了另一个原生调用或 exit 0 的脚本,或者工具确实在失败时返回 0(某些厂商 CLI)。解决:立即保存 $code = $LASTEXITCODE;对行为古怪的工具解析其输出。

git/curl 的红字让大家以为作业失败了

解决:使用工具的安静选项(git -q、curl -sS),或用 2>&1 捕获 stderr 并作为信息记录;以退出码判断成功与否。

变量 $PSNativeCommandUseErrorActionPreference 不起作用
$PSVersionTable.PSVersion; $ErrorActionPreference

原因:版本低于 7.3(只是实验功能)或是 5.1;或者 $ErrorActionPreference 是 SilentlyContinue。解决:使用 pwsh 7.4+ 和 Stop。

命令行练习
1. 在 ~/pslab/data 中运行 git status,失败时输出 “not a repo”,且不出现任何红字。
git -C ~/pslab/data status 2>$null | Out-Null
if ($LASTEXITCODE -ne 0) { 'not a repo' }
2. 让脚本以原生工具的退出码失败(供调度器使用)。
git fetch
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
场景分析
发布脚本运行 terraform plan -detailed-exitcode,它返回 0(无变更)、1(错误)或 2(有变更)。团队开启了 $PSNativeCommandUseErrorActionPreference,现在只要有变更脚本就会中止。设计修复方案。

退出码 2 是一个结果,不是错误。在子作用域中关闭首选项单独运行这条命令,保存 $code = $LASTEXITCODE,然后 switch ($code) { 0 { 'no changes' } 2 { 'changes: continue to apply' } default { throw "terraform plan failed: $code" } }。其他所有原生调用保持首选项开启,这样意外失败仍然会让运行停止。

经核实的教学视频

没有找到专门讲 $PSNativeCommandUseErrorActionPreference 或 7.x stderr 行为的经核实视频。下面的综合性错误处理视频提到了 $LASTEXITCODE;以本模块和官方文档为准。

▶
Complete PowerShell Error Handling Guide — NinjaOne IT Tech Tips
英文 · 编写健壮脚本概览

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–25 秒
画面:一个 git 进程框伸出三根管道——stdout、stderr、退出码——流入 PowerShell。
讲解:原生程序用文本和一个数字说话。
镜头 2 · 25–50 秒
画面:退出码 3 落入 $LASTEXITCODE;try/catch 框保持暗色;下一行照常执行。
讲解:默认情况下 PowerShell 只是记下来,然后继续。
镜头 3 · 50–75 秒
画面:两个开关拨动(Stop、UseErrorActionPreference);退出码 3 变成红色异常落入 catch。
讲解:启用之后,非零退出就是真正的错误。
镜头 4 · 75–90 秒
画面:robocopy 显示“1 = 已复制文件”,一个小的子作用域框把首选项关掉。
讲解:了解你的工具的退出码,并把例外限定在局部。
或测验得分 ≥ 70%

模块 4 · 六个输出流、重定向与首选项变量

21:00 – 28:00 · 数据走第 1 流;其余一切——错误、警告、详细信息、调试、信息以及 Write-Host——各有编号的流,可以分别显示、隐藏、重定向或捕获
7 分钟1 · 2 · 3 · 4 · 5 · 6★★★★☆
学习目标
  • 说出六个流对应的 Write-* cmdlet、首选项变量和记录类型。
  • 用 n>、n>>、n>&1、*>、>$null 重定向;用 -ErrorVariable、-WarningVariable、-InformationVariable 分别捕获各个流。
  • 解释为什么 Write-Host 的输出不会被 $r = … 捕获,却能被 6>&1 捕获(5.0+)。
  • 使用 -Verbose/-Debug,让诊断信息流入嵌套的高级函数。
前置:模块 1–3。重要程度:★★★★☆

What:各个流

#流写入方式首选项(默认值)通用参数记录类型
1成功(输出)直接写值、Write-Output—-OutVariable对象本身
2错误Write-Error$ErrorActionPreference(Continue)-ErrorAction、-ErrorVariableErrorRecord
3警告Write-Warning$WarningPreference(Continue)-WarningAction、-WarningVariableWarningRecord
4详细信息Write-Verbose$VerbosePreference(SilentlyContinue)-VerboseVerboseRecord
5调试Write-Debug$DebugPreference(SilentlyContinue)-DebugDebugRecord
6信息Write-Information、Write-Host$InformationPreference(SilentlyContinue)-InformationAction、-InformationVariableInformationRecord(Write-Host 会加上标签 PSHOST)
—进度Write-Progress$ProgressPreference(Continue)—不可重定向

Why:数据和诊断不能混在一起

在 Bash 中,函数在 stdout 上返回数据,所有日志行都必须发往 stderr(>&2),否则调用者的 $(…) 会捕获到垃圾。PowerShell 提供了五个非数据通道,每个都有开关。规则:只有数据走第 1 流;进度消息走 Verbose 或 Information;问题走 Warning 或 Error。这样 $servers = Get-OpsServer 捕获到的就只有服务器。

How:重定向运算符

运算符效果示例
> file、>> file第 1 流写入文件(覆盖 / 追加)Get-OpsServer > ./tmp/s.txt
n> file第 n 流写入文件2> ./tmp/err.txt、3> ./tmp/warn.txt
n>&1把第 n 流合并进成功流$all = f 2>&1
*>、*>&1所有流f *> ./tmp/all.txt
n>$null丢弃第 n 流6>$null 隐藏 Write-Host

重定向到文件使用 Out-File 的编码(7.x 中为无 BOM 的 UTF-8),并像控制台那样格式化对象——它不是结构化日志(模块 7)。

When:Verbose、Information 还是 Host

  • Write-Verbose:排错用的“我正在做什么”细节;除非调用者用 -Verbose 要求,否则不显示。在高级函数中,-Verbose 会在局部设置 $VerbosePreference,因此嵌套的高级函数会继承它(下文已验证)。
  • Write-Information:运维人员可能想看的消息,默认关闭;用 -InformationAction Continue 开启;用 -InformationVariable 连同标签一起收集。
  • Write-Host:面向交互式工具的用户显示。从 PowerShell 5.0 起,它会向第 6 流写入一个 InformationRecord,并且无论 $InformationPreference 如何都会显示。赋值不会捕获它,但 6>&1 或 -InformationVariable 可以。
  • Write-Warning:有问题但命令继续(例如“备份已存在”)。
常见误解① “Write-Host 是邪恶的,无法捕获”——从 5.0 起它属于第 6 流;但它仍然不适合用来输出数据。② “返回数据必须用 Write-Output”——直接写值效果相同。③ “*> 能捕获 verbose 输出”——仅当该流已启用;被关闭的 verbose 和 debug 记录根本不会被创建(已验证:*> 文件里没有 verbose/debug 行)。④ “重定向就能产生结构化日志”——它写的是格式化文本。⑤ “在我的函数上加 -Verbose,也会显示其中 cmdlet 的 verbose 输出”——对同一调用链上的高级函数和 cmdlet 是的;普通(非高级)函数根本没有 -Verbose 参数。

图解:一个函数,六个出口

Write-AllStreams[CmdletBinding()] 1 成功 → $x = … / 管道 2 错误 → 控制台 · $Error 3 警告 → 控制台 4 详细 → 隐藏(-Verbose) 5 调试 → 隐藏(-Debug) 6 信息 / Write-Host 由调用者控制 -ErrorAction / -WarningAction / -InformationAction-Verbose · -Debug-ErrorVariable · -WarningVariable-InformationVariable · -OutVariable2>&1 · 3> file · 6>$null · *>$xxxPreference 变量Write-Host 总会显示
图 5-6:函数决定写到哪个流;调用者决定显示什么、送到哪里

输出流路由器

选择一条消息和调用方设置;看它走哪个流、首选项是否放行、重定向把它送到哪里,以及调用者最终得到什么。

就绪。
动画对应的真实机制 每个 Write-* cmdlet 都会调用命令运行时上的 WriteXxx() 方法。运行时先检查生效的首选项(先看通用参数,再看作用域中的首选项变量)——对于 Verbose 和 Debug,若为 SilentlyContinue 则直接丢弃记录;然后追加到所有 -XxxVariable 列表,应用重定向(合并进输出管道或写入文件),最后把剩下的交给宿主,由宿主着色并加上前缀(WARNING:、VERBOSE:)。

命令表

命令用途说明
Write-Verbose 'x'诊断细节使用 -Verbose 时显示
Write-Information 'x' -Tags a,b面向运维的消息用 -InformationAction Continue 显示
Write-Warning 'x'非致命问题前缀 WARNING:
Write-Debug 'x'开发者细节7.x:-Debug 不再询问(设为 Continue)
Get-Variable *Preference显示所有首选项见下文
f 2>&1 | Group-Object { $_.GetType().Name }拆分合并后的流按记录类型
function Write-AllStreams {
    [CmdletBinding()] param()
    'success (1)'
    Write-Error       'error (2)'
    Write-Warning     'warning (3)'
    Write-Verbose     'verbose (4)'
    Write-Debug       'debug (5)'
    Write-Information 'information (6)'
    Write-Host        'host -> information (6)'
}
Write-AllStreams
success (1)
Write-AllStreams: error (2)
WARNING: warning (3)
host -> information (6)

如何验证:verbose、debug 和 Write-Information 默认隐藏;Write-Host 不隐藏。常见错误:在会被用于管道的函数里用 Write-Host 输出进度——不加 6>$null 就关不掉。生产用法:Verbose 写细节,Information 写给运维的消息,Warning 写异常情况。

合并所有流并查看记录类型

$all = Write-AllStreams -Verbose -Debug -InformationAction Continue *>&1
$all | ForEach-Object { '{0,-18} {1}' -f $_.GetType().Name, $_ }
String             success (1)
ErrorRecord        error (2)
WarningRecord      warning (3)
VerboseRecord      verbose (4)
DebugRecord        debug (5)
InformationRecord  information (6)
InformationRecord  host -> information (6)

分别捕获每个流

$data = Write-AllStreams -ErrorVariable errs -WarningVariable warns -InformationVariable infos 2>$null 3>$null 6>$null
"data:  $data"
"errs:  $($errs.Count)  warns: $($warns.Count)  infos: $($infos.Count)"
$infos | ForEach-Object { "{0} tags={1}" -f $_.MessageData, ($_.Tags -join ',') }
data:  success (1)
errs:  1  warns: 1  infos: 2
information (6) tags=
host -> information (6) tags=PSHOST

尽管 $InformationPreference 为 SilentlyContinue,-InformationVariable 仍收集到了 Write-Information 的记录;PSHOST 标签标识出 Write-Host。

Write-Host 与赋值

function Get-Report { 'report-data'; Write-Host 'Working...' }
$r = Get-Report
"captured: $r"
$r2 = Get-Report 6>&1
"captured with 6>&1: $($r2 -join ' | ')"
Get-Report 6>$null
Working...
captured: report-data
captured with 6>&1: report-data | Working...
report-data

把流写入文件

Write-AllStreams 2> ./tmp/err.txt 3> ./tmp/warn.txt > ./tmp/out.txt
Get-Content ./tmp/out.txt, ./tmp/err.txt, ./tmp/warn.txt
'---'
Write-AllStreams *> ./tmp/all.txt; Get-Content ./tmp/all.txt
host -> information (6)
success (1)
Write-AllStreams: error (2)
warning (3)
---
success (1)
Write-AllStreams: error (2)
warning (3)
information (6)
host -> information (6)

真实运行中的两点观察:第一条命令中 Write-Host 仍然显示在控制台上(第 6 流没有被重定向);第二条命令中,*> 把 Write-Information 那一行写进了文件,尽管它在控制台上默认隐藏——但没有 verbose 或 debug 行,因为首选项为 SilentlyContinue 时这些记录根本不会被创建。

首选项变量与嵌套的 -Verbose

Get-Variable *Preference | Sort-Object Name | Format-Table Name, Value -AutoSize
function Inner { [CmdletBinding()] param() Write-Verbose 'inner verbose' }
function Outer { [CmdletBinding()] param() Write-Verbose 'outer verbose'; Inner }
Outer -Verbose
Name                                               Value
----                                               -----
ConfirmPreference                                   High
DebugPreference                         SilentlyContinue
ErrorActionPreference                           Continue
InformationPreference                   SilentlyContinue
ProgressPreference                              Continue
PSNativeCommandUseErrorActionPreference            False
VerbosePreference                       SilentlyContinue
WarningPreference                               Continue
WhatIfPreference                                   False
VERBOSE: outer verbose
VERBOSE: inner verbose

目标:让一个 OpsKit 风格的函数拥有干净的输出流,并从调用方分别捕获每个流。环境:~/pslab。成本:~/pslab/tmp 中的几个文件。

一个输出流规范的函数:
function Get-ProdServer {
    [CmdletBinding()] param()
    Write-Verbose 'reading ./data/servers.csv'
    $rows = Import-Csv ./data/servers.csv
    Write-Information "loaded $($rows.Count) rows" -Tags 'inventory'
    $prod = $rows | Where-Object Env -eq 'prod'
    if (@($prod | Where-Object Monitored -eq 'false').Count) { Write-Warning 'some prod servers are not monitored' }
    $prod
}
$s = Get-ProdServer -InformationVariable info -WarningVariable warn 3>$null
"servers=$(@($s).Count) info='$($info.MessageData)' warning='$warn'"

实际输出(7.6.10):servers=6 info='loaded 12 rows' warning='some prod servers are not monitored'——prod 中的 db-01 和 bastion-01 的 Monitored = false。

只在需要时打开细节:Get-ProdServer -Verbose | Out-Null 会显示 VERBOSE 行;其他不变。
把流记录到不同文件(类似 Bash 的 >out 2>err):Get-ProdServer > ./tmp/prod.txt 3> ./tmp/prod.warn.txt,然后读取这两个文件。
清理:Remove-Item ./tmp/*.txt

案例 1:把 “Connecting…” 当作数据返回的函数

问题:$ip = Get-VmIp vm01 有时得到 Connecting... 10.0.0.4,导致下一条命令出错。根因:函数用 Write-Output 'Connecting...'(第 1 流)输出进度消息。修复:进度用 Write-Verbose;只有 IP 走第 1 流。用 Bash 的话说:日志进 stderr,数据进 stdout。

案例 2:没有任何诊断信息的定时任务

问题:夜间任务失败时,日志里只有最后的错误。根因:细节都用 Write-Verbose 写的,而它默认关闭。修复:定时任务用 -Verbose 和 *>> job.log 运行;更好的做法是用 OpsKit 的 JSON 行日志写结构化事件(模块 7),verbose 留给人看。

案例 3:“容器里的 Write-Host 输出不见了”

问题:工程师用 $o = ./report.ps1 6>&1 捕获脚本输出,结果数据里突然多了几行。根因:合并第 6 流把 Write-Host 记录也带进了变量。修复:按类型过滤($o | Where-Object { $_ -isnot [System.Management.Automation.InformationRecord] }),或用 -InformationVariable 单独捕获信息流。

常见错误与解决

-Verbose 对我的函数不起作用

原因:函数不是高级函数(没有 [CmdletBinding()] 或 [Parameter()]),所以 -Verbose 根本不是参数——或者它被按位置传给了别的参数。

(Get-Command MyFunc).CmdletBinding
我的变量里 ErrorRecord 和数据混在一起

原因:2>&1 或 *>&1。解决:按类型拆分,或改用 -ErrorVariable 而不是合并。

Write-Information 的消息从不显示

解决:调用时加 -InformationAction Continue,或在脚本中设置 $InformationPreference = 'Continue'。

进度条拖慢了我的文件下载循环

解决:在非交互脚本中设置 $ProgressPreference = 'SilentlyContinue'(进度不是可重定向的流)。

命令行练习
1. 运行 Write-AllStreams,只以字符串形式保留警告。
Write-AllStreams 3>&1 2>$null 6>$null | Where-Object { $_ -is [System.Management.Automation.WarningRecord] } | ForEach-Object Message
2. 屏蔽一个话多的脚本的 Write-Host 行,但保留其数据。
$data = ./chatty.ps1 6>$null
场景分析
一个共享模块在每个函数里都用 Write-Host 打印彩色进度。自动化团队想要静默运行并获得机器可读的执行记录;服务台想要彩色文本。如何在不分叉模块的情况下同时满足?

把 Write-Host 进度替换为 Write-Information(带标签)和 Write-Verbose。交互用户在配置文件里设置 $InformationPreference = 'Continue'(或模块提供 -Show 开关);自动化静默运行并收集 -InformationVariable,其中保留了标签和时间戳(TimeGenerated),可用于结构化日志。如果为了颜色必须保留 Write-Host,自动化仍然可以用 6>$null 丢弃它,或通过 -InformationVariable 捕获它,因为它属于第 6 流。

经核实的教学视频

没有找到专门讲 PowerShell 7 六个输出流与重定向的经核实视频。以下面的文档为参考;John Savill 的大师课涉及输出与管道:

▶
PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
英文 · 输出、管道与基础知识

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:一个函数伸出六根彩色管道;只有绿色的(1)流入变量。
讲解:数据走第一流;其他一切各走各的车道。
镜头 2 · 20–45 秒
画面:标着“首选项”的阀门关闭了 verbose 和 debug 管道;-Verbose 打开其中一个。
讲解:首选项决定显示什么;通用参数覆盖首选项。
镜头 3 · 45–70 秒
画面:2>&1 把红管弯进绿管;3> file 把黄色引进一个文档。
讲解:重定向可以合并或转移任何流。
镜头 4 · 70–90 秒
画面:Write-Host 标注“第 6 流”和 PSHOST 标签。
讲解:Write-Host 是保证显示的信息。适合给人看,不适合输出数据。
或测验得分 ≥ 70%

模块 5 · 严格模式与防御式编程

28:00 – 35:00 · 没有严格模式时,变量名或属性名的拼写错误会悄悄变成 $null;Set-StrictMode -Version Latest 把这些静默缺陷变成错误,而守卫语句、验证特性和正确的 $null 比较会把错误输入挡在门外
7 分钟Set-StrictMode · [Validate*()]★★★★☆
学习目标
  • 复现四个静默缺陷(变量拼错、属性或哈希表键拼错、用方法调用语法调用函数、越界索引),并用 Set-StrictMode -Version Latest 逐一捕获。
  • 掌握严格模式的作用域规则:作用于当前作用域及其子作用域,模块有自己的设置。
  • 编写守卫语句和验证特性(ValidateRange、ValidateSet、带 ErrorMessage 的 ValidateScript),并把 $null 放在比较的左边。
  • 在边界(脚本入口、模块作用域)设置 -ErrorAction Stop / $ErrorActionPreference = 'Stop',而不是到处设置。
前置:模块 1–2;第 3 课(参数特性)。重要程度:★★★★☆

What:各严格模式版本检查什么

检查项关闭(默认)-Version 1.02.03.0 / Latest
读取未初始化的变量($destinaton)$null报错(字符串内除外)报错报错
读取不存在的属性($o.Nmae)$null—报错报错——用点号访问不存在的哈希表键也会报错(已验证)
像调用方法一样调用函数 f(1,2)传入一个数组—报错报错
没有名字的变量 ${}允许—报错报错
索引越界 $a[5]$null——报错

Latest 表示当前 PowerShell 所知的最高版本(7.6 上为 3.0)。与 Bash 对比:set -u 只覆盖第一行。

Why:拼写错误是最便宜就能预防的缺陷

没有严格模式时,如果 $fileName 被误写成 $fileNmae,Remove-Item "$backupDir/$fileName" 就变成了 Remove-Item "$backupDir/"。这不是假设——它就是每种 shell 里经典的 rm -rf "$DIR/" 事故。严格模式会在危险命令执行之前,把读取未设置变量变成错误。OpsKit v0.3 在 OpsKit.psm1 顶部设置了 Set-StrictMode -Version Latest,覆盖模块内所有函数,而不影响任何调用方代码。

How:防御模式

模式示例防止什么
守卫语句(快速失败)if (-not (Test-Path -LiteralPath $Source -PathType Container)) { $PSCmdlet.ThrowTerminatingError(…) }对错误或缺失的输入进行操作;深层嵌套
验证特性[ValidateRange(1,365)][int]$Keep、[ValidateSet('dev','staging','prod')]、[ValidateScript({…}, ErrorMessage = '…')]错误值根本到不了你的代码;在绑定时报出清晰的消息
$null 放左边if ($null -eq $result)$array -eq $null 会过滤数组而不是测试它
强制为数组@($servers).Count单个对象或 $null 在旧代码中没有可靠的 .Count 语义
对可选键用 ContainsKey / 索引语法if ($cfg.ContainsKey('Backup'))、$h['Kepe']可选设置引发严格模式错误(索引语法返回 $null)
在边界处 Stop脚本 / psm1 顶部:$ErrorActionPreference = 'Stop';局部例外用 -ErrorAction Ignore某一步失败后仍继续执行

When:作用域规则

  • Set-StrictMode 影响它所在的作用域及所有子作用域;子作用域可以只对自己关闭(Set-StrictMode -Off)而不改变父作用域(下文已验证)。
  • 模块有自己的会话状态:你脚本里的严格模式不会作用到模块内部,模块的设置也不会泄露出来。
  • 如果你经常在交互式会话中粘贴示例代码,就不要在配置文件里开启 Set-StrictMode——但脚本和模块里一定要开。
常见误解① “严格模式就像 set -e”——它捕获的是编码错误,不是失败的命令;要和 $ErrorActionPreference = 'Stop' 配合使用。② “严格模式下缺失的哈希表键没问题”——在 Latest 下用点号访问会报错(已验证);请用 ContainsKey 或 $h['key']。③ “$x -eq $null 与 $null -eq $x 等价”——当 $x 是数组时不等价。④ “验证只是文档”——它在绑定时运行,在函数体执行前就报错。⑤ “我脚本里的严格模式能保护我调用的模块”——每个模块自行决定。

图解:一个参数的层层防御

调用者输入-Keep 0 1 · 参数绑定类型 [int][ValidateRange(1,365)][Parameter(Mandatory)]→ 函数体前报错 2 · 守卫语句Test-Path 源目录配置有 Backup 吗?ThrowTerminatingError带稳定 id 3 · 函数体StrictMode Latest:拼写错误 → 报错EAP Stop:失败的命令 → 报错 4 · 变更ShouldProcess(模块 6)幂等先检查
图 5-7:尽早拒绝错误输入;让严格模式和 Stop 捕获你自己的错误;然后才去修改任何东西

严格模式检查器

选择一行有缺陷的代码,比较严格模式关闭与 -Version Latest 时的结果。所有输出均在 7.6.10 上复现。

就绪。
动画对应的真实机制 严格模式按作用域保存。引擎计算变量、成员或索引表达式时,会检查当前作用域生效的严格模式版本;若检查失败,就抛出语句终止的 RuntimeException(例如 VariableIsUndefined 或 PropertyNotFoundStrict),而不是返回 $null。方法调用检查发生在用括号和逗号分隔的参数调用命令时。

命令表

命令用途说明
Set-StrictMode -Version Latest开启全部检查每个脚本和 .psm1 的顶部
Set-StrictMode -Off在当前作用域关闭用于一段旧代码
[ValidateRange(1, 30)]数值范围也可用 Positive、NonNegative
[ValidateSet('a','b')]允许值 + Tab 补全不区分大小写
[ValidateScript({ … }, ErrorMessage = '… {0}')]自定义检查,消息可读{0} 为传入的值
[ValidateNotNullOrEmpty()]拒绝 '' / $null还有 ValidateNotNullOrWhiteSpace(7.4+)
$null -eq $x空值测试$null 永远放左边

严格模式关闭时的四个静默缺陷

$cfg = Import-PowerShellDataFile ./data/opskit.config.psd1
"keep=[$($cfg.Backup.Kepe)]  dest=[$destinaton]"
function Add-Numbers($a, $b) { $a + $b }
Add-Numbers(1, 2)
$list = 1, 2, 3; "fourth=[$($list[3])]"
keep=[]  dest=[]
1
2
fourth=[]

完全没有报错。Add-Numbers(1, 2) 把数组 1,2 传给了 $a,$b 什么也没有,所以返回的是这个数组。

同样的缺陷,严格模式 Latest(每个都在全新会话中运行)

Set-StrictMode -Version Latest
$cfg = Import-PowerShellDataFile ./data/opskit.config.psd1
"dest=[$destinaton]"
InvalidOperation: The variable '$destinaton' cannot be retrieved because it has not been set.
Set-StrictMode -Version Latest
$o = [pscustomobject]@{ Name = 'web-01' }
$o.Nmae
PropertyNotFoundException: The property 'Nmae' cannot be found on this object. Verify that the property exists.
Set-StrictMode -Version Latest
$cfg = Import-PowerShellDataFile ./data/opskit.config.psd1
"hashtable key: [$($cfg.Backup.Kepe)]"
PropertyNotFoundException: The property 'Kepe' cannot be found on this object. Verify that the property exists.
hashtable key: []

在字符串内部,失败的子表达式会被报告并求值为空——字符串本身仍然会生成。若单独一行写 $cfg.Backup.Kepe,该语句会停止。

Set-StrictMode -Version Latest
function Add-Numbers($a, $b) { $a + $b }
Add-Numbers(1, 2)
InvalidOperation: The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic.
Set-StrictMode -Version Latest
$list = 1, 2, 3
$list[3]
OperationStopped: Index was outside the bounds of the array.

作用域:子作用域可以关闭,父作用域保持开启

Set-StrictMode -Version Latest
function Get-Inner { $undefinedInner }
& { Set-StrictMode -Off; "child scope off: [$undefinedChild]" }
"script scope still Latest:"
Get-Inner
child scope off: []
script scope still Latest:
InvalidOperation: The variable '$undefinedInner' cannot be retrieved because it has not been set.

$null 放左边

$servers = Import-Csv ./data/servers.csv
$none = $servers | Where-Object Env -eq 'qa'
"none -eq null: " + ($none -eq $null)
$arr = @($null, 1, $null)
"arr -eq null returns: " + ($arr -eq $null).Count + " items -> if() sees " + [bool]($arr -eq $null)
"null -eq arr: " + ($null -eq $arr)
"count of none: " + @($none).Count
none -eq null: True
arr -eq null returns: 2 items -> if() sees True
null -eq arr: False
count of none: 0

数组在左边时,-eq 是一个过滤器:它返回了两个 $null 元素,而 2 个元素的数组为真值。$null -eq $arr 才是在问真正的问题。

验证特性

function Set-OpsKeep {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][ValidateRange(1, 30)][int]$Keep,
        [ValidateSet('dev', 'staging', 'prod')][string]$Environment = 'dev',
        [ValidateScript({ Test-Path -LiteralPath $_ -PathType Container }, ErrorMessage = 'Folder not found: {0}')]
        [string]$Destination = '.'
    )
    "ok: keep $Keep in $Environment at $Destination"
}
Set-OpsKeep -Keep 7
Set-OpsKeep -Keep 0
Set-OpsKeep -Keep 7 -Environment qa
Set-OpsKeep -Keep 7 -Destination ./nope
ok: keep 7 in dev at .
Set-OpsKeep: Cannot validate argument on parameter 'Keep'. The 0 argument is less than the minimum allowed range of 1. Supply an argument that is greater than or equal to 1 and then try the command again.
Set-OpsKeep: Cannot validate argument on parameter 'Environment'. The argument "qa" does not belong to the set "dev,staging,prod" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.
Set-OpsKeep: Cannot validate argument on parameter 'Destination'. Folder not found: ./nope

如何验证:验证错误属于参数绑定错误(语句终止,ParameterArgumentValidationError),在函数体任何一行执行之前抛出。常见错误:在函数体里、副作用已经发生之后才用 if 验证。生产用法:OpsKit 中所有控制删除行为的参数(-Keep)都有范围限制。

目标:通过开启严格模式找出一个小脚本中的缺陷。环境:~/pslab。成本:无。

保存为 ~/pslab/scripts/Get-BackupPlan.ps1(其中有三个故意的缺陷):
param([int]$Keep = 7)
$cfg = Import-PowerShellDataFile (Join-Path $PSScriptRoot '..' 'data' 'opskit.config.psd1')
$dest = $cfg.Backup.Destinaton                       # bug 1: typo in key
$excluded = $cfg.Backup.Exclude
"Plan: keep $Keep archives in [$dest], skip $($exlcuded -join ', ')"   # bug 2: typo in variable
$first = @(Get-ChildItem (Join-Path $PSScriptRoot '..' 'data') -File)[10]  # bug 3: only 4 files
"First file to back up: $($first.Name)"
运行:./scripts/Get-BackupPlan.ps1
Plan: keep 7 archives in [], skip
First file to back up:

三个缺陷,零个错误。

在第二行(param 之后)加入 Set-StrictMode -Version Latest,用 pwsh -NoProfile -File ./scripts/Get-BackupPlan.ps1 运行:
PropertyNotFoundException: C:\Users\labadmin\pslab\scripts\Get-BackupPlan.ps1:4
Line |
   4 |  $dest = $cfg.Backup.Destinaton                       # bug 1: typo in …
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | The property 'Destinaton' cannot be found on this object. Verify that the property exists.
InvalidOperation: C:\Users\labadmin\pslab\scripts\Get-BackupPlan.ps1:6
Line |
   6 |  "Plan: keep $Keep archives in [$dest], skip $($exlcuded -join ', ')"  …
     |                                 ~~~~~
     | The variable '$dest' cannot be retrieved because it has not been set.
OperationStopped: C:\Users\labadmin\pslab\scripts\Get-BackupPlan.ps1:7
Line |
   7 |  $first = @(Get-ChildItem (Join-Path $PSScriptRoot '..' 'data') -File) …
     |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Index was outside the bounds of the array.
InvalidOperation: C:\Users\labadmin\pslab\scripts\Get-BackupPlan.ps1:8
Line |
   8 |  "First file to back up: $($first.Name)"
     |                            ~~~~~~
     | The variable '$first' cannot be retrieved because it has not been set.
First file to back up:

每个严格模式错误都是语句终止的,所以脚本继续运行并产生了连锁错误($dest 和 $first 从未被赋值)。$exlcuded 拼写错误被 $dest 的错误挡住了;修复缺陷 1 后它才会出现。结论:严格模式能发现缺陷,但只有 $ErrorActionPreference = 'Stop' 或 try/catch 才能让脚本在第一个错误处停下——两行都要加。

让它更具防御性:给 $Keep 加上 [ValidateRange(1, 365)],并加一条守卫语句 if (-not $cfg.ContainsKey('Backup')) { throw 'config has no Backup section' }。
清理:保留该脚本(它是无害的),或 Remove-Item ./scripts/Get-BackupPlan.ps1。

案例 1:删掉整个共享目录的空变量

问题:一个清理脚本执行 Remove-Item "$root\$tenantFolder" -Recurse -Force;一次重构把 $tenantFolder 改名为 $tenantDir,却只改了一处。路径变成了 $root\。根因:没有严格模式,没有验证。修复:Set-StrictMode -Version Latest;一条守卫语句,拒绝删除已知根目录下深度不足两级的任何路径;SupportsShouldProcess,让变更可以预览(模块 6)。

案例 2:永远不为真的 if ($result -eq $null)

问题:一次健康检查报告“没有失败的主机”,而实际上有好几台失败了。根因:$failed 是一个含有 $null 占位元素的数组;$failed -eq $null 返回了那些空元素(真值),分支逻辑因此颠倒。修复:空值检查用 $null -eq $failed,判空用 @($failed).Count -eq 0。PSScriptAnalyzer 规则 PSPossibleIncorrectComparisonWithNull 会标出这种写法(第 8 课)。

案例 3:升级后严格模式“弄坏”了一个旧模块

问题:团队在自己的模块中加入 Set-StrictMode -Version Latest 后,对一个第三方模块的调用开始失败。根因:其实不是——严格模式不跨越模块边界。真正的原因是他们自己的代码用点号读取了一个可选配置键。修复:可选设置用 $cfg['Optional'] 或 ContainsKey。

常见错误与解决

The variable '$x' cannot be retrieved because it has not been set

原因:拼写错误,或变量只在某个分支中被赋值。解决:改正名称,或在分支之前初始化($x = $null)。

The property 'X' cannot be found on this object

原因:拼写错误、可选属性/键,或者对象的类型和你以为的不同。

$obj | Get-Member -MemberType Properties
$h.ContainsKey('X'); $h['X']
$obj.PSObject.Properties.Name -contains 'X'
The function or command was called as if it were a method

解决:用空格分隔参数调用命令:Add-Numbers 1 2 或 Add-Numbers -a 1 -b 2。

Cannot validate argument on parameter …

原因:这是设计如此。解决:传入有效值;用 (Get-Command f).Parameters['Keep'].Attributes 查看特性。

命令行练习
1. 在严格模式下安全地从配置中读取 Backup.Keep,键不存在时默认为 7。
Set-StrictMode -Version Latest
$cfg  = Import-PowerShellDataFile ./data/opskit.config.psd1
$keep = if ($cfg.ContainsKey('Backup') -and $cfg.Backup.ContainsKey('Keep')) { $cfg.Backup.Keep } else { 7 }
2. 写一个只接受已存在文件夹的参数,并用通俗的话报错。
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Container }, ErrorMessage = 'Not a folder: {0}')]
[string]$Destination
场景分析
一位评审者说:“.psm1 顶部有严格模式和 $ErrorActionPreference = 'Stop' 就够了,不需要验证特性。”你同意吗?

不同意。严格模式捕获的是你代码中的错误;Stop 捕获的是失败的命令。两者都不知道 -Keep 0 会删光所有备份——那是一个完全合法的整数。验证特性在边界处表达业务规则,在任何副作用之前失败,产生指明参数名的消息,并在 Get-Help 中记录契约。三层都要用。

经核实的教学视频

没有找到专门讲 Set-StrictMode 的经核实视频。请以文档为准;下面的错误处理指南涵盖一般的防御式脚本编写。

▶
Complete PowerShell Error Handling Guide — NinjaOne IT Tech Tips
英文 · 编写健壮的脚本

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–25 秒
画面:Remove-Item "$root/$fileNmae";变量淡出成空,路径缩短为 $root/。
讲解:一个拼写错误,目标就变成了整个文件夹。
镜头 2 · 25–50 秒
画面:Set-StrictMode Latest 打开;同一行现在以红色的 “has not been set” 停下。
讲解:严格模式把静默的空值变成错误。
镜头 3 · 50–75 秒
画面:一个带三个特性徽章的参数把 -Keep 0 挡在门外。
讲解:在绑定时验证,在任何变更发生之前。
镜头 4 · 75–90 秒
画面:$null -eq $x,左边的 $null 被高亮。
讲解:null 永远放左边。
或测验得分 ≥ 70%

模块 6 · 安全变更:SupportsShouldProcess、-WhatIf / -Confirm 与幂等

35:00 – 42:00 · 任何修改状态的命令都应该能说出它将做什么(-WhatIf)、在动手前询问(-Confirm)、第二次运行时什么也不做(幂等)——而且你必须验证 -WhatIf 真的传到了它调用的每一个命令
7 分钟ShouldProcess · ConfirmImpact★★★★★
学习目标
  • 添加 [CmdletBinding(SupportsShouldProcess, ConfirmImpact = …)],并把每一处变更包在 if ($PSCmdlet.ShouldProcess($target, $action)) 中。
  • 预测 PowerShell 何时会询问:ConfirmImpact 与 $ConfirmPreference 的比较、-Confirm、-Confirm:$false,以及在 -NonInteractive 下会发生什么。
  • 了解 -WhatIf 如何传递(它在你的函数作用域中设置 $WhatIfPreference)——并复现它不会传到 Compress-Archive 的情形。
  • 编写幂等的变更:先检查当前状态;第二次运行什么也不改。
前置:第 3 课(高级函数)、模块 1–5。重要程度:★★★★★

What:ShouldProcess 契约

组成部分作用
[CmdletBinding(SupportsShouldProcess)]给函数加上 -WhatIf 和 -Confirm(没有它时使用 -WhatIf 会报错:A parameter cannot be found that matches parameter name 'WhatIf'——已验证)
$PSCmdlet.ShouldProcess($target, $action)应当执行变更时返回 $true。使用 -WhatIf 时打印 What if: Performing the operation "$action" on target "$target". 并返回 $false;使用 -Confirm 时询问;使用 -Verbose 时以 VERBOSE 打印同样的消息并返回 $true
ConfirmImpact = 'Low' | 'Medium' | 'High'命令的危险程度。若影响级别 ≥ $ConfirmPreference(默认 High),PowerShell 会自动询问
$WhatIfPreference-WhatIf 会在你的函数作用域中把它设为 $true;你调用的命令会读取它

Why:先预览,后变更

Bash 工具各自发明自己的 --dry-run。在 PowerShell 中,-WhatIf 是统一的契约:每个会修改状态的内置 cmdlet 都支持它,所以 Get-ChildItem … | Remove-Item -WhatIf 总是有效。你自己的函数只需一个特性就能加入这个契约——但这个保证只取决于你的实现:每一处状态变更都必须位于 ShouldProcess 之后,或位于会遵循继承来的 $WhatIfPreference 的命令中。

How:传递——能到达你调用的哪些命令

被调用的命令会自动遵循你的 -WhatIf 吗?验证结果
编译型 cmdlet(Remove-Item、Copy-Item、New-Item、Add-Content)会Copy-Item 打印了 What if: … "Copy File"
同一模块 / 脚本中的函数(例如 Invoke-OpsBackup 调用的 Remove-OpsBackup)会——动态作用域链能找到你的 $WhatIfPreference轮转打印了 What if: … "Remove old backup"
另一个脚本模块中的函数(例如 Microsoft.PowerShell.Archive 1.2.7 中的 Compress-Archive)不会——它们的作用域链先到自己的模块,再到全局作用域,而不会到你的函数(它们能看到设置在全局作用域中的首选项——包括 pwsh -File 脚本的顶层,因为它就运行在全局作用域中)尽管有 -WhatIf,zip 仍被创建;一个测试模块函数报告 WhatIfPreference=False 并写入了文件
.NET 方法([IO.File]::Delete())和原生程序永远不会—

因此:在每一处变更外包上你自己的 ShouldProcess 调用;调用其他模块的函数时显式传入 -WhatIf:$WhatIfPreference(或在你自己确认之后传 -Confirm:$false)。反过来,即使在 WhatIf 模式下也必须写入的日志,需要 -WhatIf:$false(或用 .NET API)——已验证:在以 -WhatIf 调用的函数中,Add-Content 没有写入日志。

When:ConfirmImpact 与 $ConfirmPreference

ConfirmImpact$ConfirmPreference = High(默认)= Medium= None
Low不询问不询问不询问
Medium(OpsKit 备份)不询问询问不询问
High(例如删除生产数据)询问询问不询问

-Confirm 总会询问;-Confirm:$false 从不询问。在 pwsh -NonInteractive 会话中,询问会变成错误:Exception calling "ShouldProcess" with "2" argument(s): "PowerShell is in NonInteractive mode…"(已验证)——所以调用 High 影响级别命令的定时任务必须有意识地传入 -Confirm:$false。幂等意味着“先检查再变更”:测试目标是否已处于期望状态,是就提前返回,这样重试和重跑都是安全的。

常见误解① “有了 SupportsShouldProcess 我的函数就安全了”——只有位于 ShouldProcess 内部(或在继承首选项的 cmdlet 中)的部分才会被跳过。② “-WhatIf 会传到我调用的一切”——传不到其他脚本模块的函数、.NET 调用或原生工具(已用 Compress-Archive 验证)。③ “ConfirmImpact High 就一定会询问”——调用者设置了 $ConfirmPreference = 'None' 或传入 -Confirm:$false 时不会。④ “-WhatIf 输出是可靠的计划”——它只和你的代码一样可靠;OpsKit 的轮转预览比真实运行少显示一次删除(模块 8)。⑤ “-Force 就等于 -Confirm:$false”——只有你这样实现时才是。

流程图:ShouldProcess 的决策

$PSCmdlet.ShouldProcess(t, a) $WhatIfPreference? true 打印 “What if: …”返回 $false -Confirm,或 ConfirmImpact ≥$ConfirmPreference ? 是 询问 Y/A/N/L/S由回答决定-NonInteractive → 异常 否 -Verbose?打印 VERBOSE 行 返回 $true → 执行变更 变更内部cmdlet:继承首选项同模块函数:继承其他脚本模块:不继承.NET / 原生:永不
图 5-8:一次方法调用做出决定;你在 if 块里做了什么,决定了预览是否诚实

ShouldProcess 决策路径

选择 Remove-OldTmp(或一个 High 影响级别命令)的调用方式,跟随它的决策。

就绪。
动画对应的真实机制 -WhatIf 和 -Confirm 是通用参数;绑定后,引擎在函数作用域中把 $WhatIfPreference / $ConfirmPreference 设为局部变量。ShouldProcess 读取它们,比较 ConfirmImpact 与 $ConfirmPreference,并与宿主交互。你调用的编译型 cmdlet 会从调用者的作用域查找这些首选项变量;而另一个模块中的脚本函数通过它自己模块的会话状态解析变量,所以永远看不到你的。

命令表

语法用途说明
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]启用 -WhatIf/-Confirm默认影响级别为 Medium
$PSCmdlet.ShouldProcess($target, $action)每次变更前征求许可还有 1 个和 3 个参数的重载
$PSCmdlet.ShouldContinue($q, $caption)即使没有 -Confirm 也额外确认与 -Force 开关搭配
-WhatIf:$WhatIfPreference显式传递预览模式调用其他模块的函数时使用
-WhatIf:$false总是执行(日志)谨慎使用,只用于没有副作用的写入
$ConfirmPreference = 'None'在当前作用域中从不询问优先对单次调用使用 -Confirm:$false
function Remove-OldTmp {
    [CmdletBinding(SupportsShouldProcess)]
    param([string]$Path = './tmp', [int]$Keep = 2)
    $old = Get-ChildItem -LiteralPath $Path -File -Filter 't?.txt' | Sort-Object Name -Descending | Select-Object -Skip $Keep
    foreach ($f in $old) {
        if ($PSCmdlet.ShouldProcess($f.Name, 'Delete old temp file')) {
            Remove-Item -LiteralPath $f.FullName
            "deleted $($f.Name)"
        }
    }
}
1..4 | ForEach-Object { Set-Content "./tmp/t$_.txt" $_ }
Remove-OldTmp -WhatIf
(Get-ChildItem ./tmp -Filter 't?.txt').Name -join ','
Remove-OldTmp
(Get-ChildItem ./tmp -Filter 't?.txt').Name -join ','
What if: Performing the operation "Delete old temp file" on target "t2.txt".
What if: Performing the operation "Delete old temp file" on target "t1.txt".
t1.txt,t2.txt,t3.txt,t4.txt
deleted t2.txt
deleted t1.txt
t3.txt,t4.txt

如何验证:使用 -WhatIf 后,文件列表没有变化。常见错误:预览里的目标字符串毫无意义("file");应使用运维人员能认出的名称或路径。生产用法:把 -WhatIf 纳入每张变更单:把它的输出贴进去作为计划。

没有自己的 ShouldProcess:cmdlet 仍然继承

function Clear-TmpNaive {
    [CmdletBinding(SupportsShouldProcess)]
    param()
    Get-ChildItem ./tmp -Filter 't?.txt' | Remove-Item     # no ShouldProcess call of our own
}
Clear-TmpNaive -WhatIf
What if: Performing the operation "Remove File" on target "C:\Users\labadmin\pslab\tmp\t1.txt".
What if: Performing the operation "Remove File" on target "C:\Users\labadmin\pslab\tmp\t2.txt".
What if: Performing the operation "Remove File" on target "C:\Users\labadmin\pslab\tmp\t3.txt".
What if: Performing the operation "Remove File" on target "C:\Users\labadmin\pslab\tmp\t4.txt".

……但另一个脚本模块中的函数不继承

# ./tmp/PropDemo/PropDemo.psm1
function Save-DataZip {
    [CmdletBinding(SupportsShouldProcess)]
    param([string]$Destination)
    # No ShouldProcess call of our own: we rely on -WhatIf "flowing" into the commands we call
    Compress-Archive -LiteralPath (Join-Path $PWD 'data/servers.csv') -DestinationPath $Destination
    Copy-Item -LiteralPath (Join-Path $PWD 'data/servers.csv') -Destination ($Destination + '.csv')
}
Import-Module ./tmp/PropDemo/PropDemo.psm1 -Force
Save-DataZip -Destination ./tmp/prop.zip -WhatIf
"zip created anyway: $(Test-Path ./tmp/prop.zip)   csv copied: $(Test-Path ./tmp/prop.zip.csv)"
(Get-Command Compress-Archive).Module.ModuleType
What if: Performing the operation "Copy File" on target "Item: C:\Users\labadmin\pslab\data\servers.csv Destination: C:\Users\labadmin\pslab\tmp\prop.zip.csv".
zip created anyway: True   csv copied: False
Manifest

直接带 -WhatIf 调用时,Compress-Archive 会遵循它(已验证:What if: Performing the operation "Compress-Archive" …,没有生成文件)。在 Save-DataZip 内部,编译型的 Copy-Item 遵循了继承来的首选项;Compress-Archive——一个脚本模块中的函数(清单的模块类型显示为 Manifest;其代码是一个 .psm1)——却创建了 zip。这就是 Invoke-OpsBackup 只在自己的 ShouldProcess 块中调用 Compress-Archive 的原因。

WhatIf 运行中的日志

function Write-RunLog {
    [CmdletBinding(SupportsShouldProcess)]
    param()
    if ($PSCmdlet.ShouldProcess('target', 'Change')) { 'changed' }
    Add-Content -LiteralPath ./tmp/run.log -Value 'run finished'
}
Write-RunLog -WhatIf
"log exists: $(Test-Path ./tmp/run.log)"
What if: Performing the operation "Change" on target "target".
What if: Performing the operation "Add Content" on target "Path: C:\Users\labadmin\pslab\tmp\run.log".
log exists: False

Confirm、ConfirmImpact 与 -NonInteractive

function Remove-Thing {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param([string]$Name)
    if ($PSCmdlet.ShouldProcess($Name, 'Remove')) { "removed $Name" }
}
Remove-Thing -Name a -Confirm:$false
$ConfirmPreference = 'None'; Remove-Thing -Name b; $ConfirmPreference = 'High'
Remove-Thing -Name c                 # in pwsh -NonInteractive
removed a
removed b
MethodInvocationException:
Line |
   4 |      if ($PSCmdlet.ShouldProcess($Name, 'Remove')) { "removed $Name" }
     |          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "ShouldProcess" with "2" argument(s): "PowerShell is in NonInteractive mode. Read and Prompt functionality is not available."

WhatIfPreference、对不支持的函数使用 -WhatIf、幂等

function Remove-NoSupport { [CmdletBinding()] param() 'ran' }
Remove-NoSupport -WhatIf

$WhatIfPreference = $true
New-Item ./tmp/should-not-exist.txt
Test-Path ./tmp/should-not-exist.txt
$WhatIfPreference = $false

function Set-OpsFolder {
    [CmdletBinding(SupportsShouldProcess)]
    param([Parameter(Mandatory)][string]$Path)
    if (Test-Path -LiteralPath $Path -PathType Container) { Write-Verbose "exists: $Path"; return }
    if ($PSCmdlet.ShouldProcess($Path, 'Create folder')) {
        $null = New-Item -ItemType Directory -Path $Path
        "created $Path"
    }
}
Set-OpsFolder ./tmp/idem -Verbose
Set-OpsFolder ./tmp/idem -Verbose
Remove-Item ./tmp/idem
Remove-NoSupport: A parameter cannot be found that matches parameter name 'WhatIf'.
What if: Performing the operation "Create File" on target "Destination: C:\Users\labadmin\pslab\tmp\should-not-exist.txt".
False
VERBOSE: Performing the operation "Create folder" on target "./tmp/idem".
created ./tmp/idem
VERBOSE: exists: ./tmp/idem

目标:证明 -WhatIf 能传到哪里,并修复一个在预览模式下“撒谎”的函数。环境:~/pslab/tmp。成本:几个小文件。

复现传递缺口:根据“命令”分页创建 ./tmp/PropDemo/PropDemo.psm1,导入后运行 Save-DataZip -Destination ./tmp/prop.zip -WhatIf,确认 zip 存在。
修复它:把工作包进你自己的检查,并显式传递首选项:
function Save-DataZip {
    [CmdletBinding(SupportsShouldProcess)]
    param([string]$Destination)
    if ($PSCmdlet.ShouldProcess($Destination, 'Create archive')) {
        Compress-Archive -LiteralPath (Join-Path $PWD 'data/servers.csv') -DestinationPath $Destination -Confirm:$false
        Copy-Item -LiteralPath (Join-Path $PWD 'data/servers.csv') -Destination ($Destination + '.csv')
    }
}

删除 ./tmp/prop.zip,用 -Force 重新导入,带 -WhatIf 运行:只有一行 “What if”,没有文件。不带它运行:两个文件都生成(7.6.10 上已验证)。

检查首选项的模块边界:
Import-Module ./OpsKit/OpsKit.psd1 -Force
"caller EAP after import: $ErrorActionPreference"
Get-Item ./nope; 'caller continued (module Stop did not leak)'
caller EAP after import: Continue
Get-Item: Cannot find path 'C:\Users\labadmin\pslab\nope' because it does not exist.
caller continued (module Stop did not leak)
清理:Remove-Module PropDemo -ErrorAction Ignore; Remove-Item ./tmp/PropDemo, ./tmp/prop.zip, ./tmp/prop.zip.csv, ./tmp/t?.txt -Recurse -ErrorAction Ignore

案例 1:删光了归档存储桶的“演练”

问题:工程师在变更窗口前运行内部的 Invoke-Retention -WhatIf;预览看起来没问题,可真实数据已经没了。根因:该函数用另一个模块的函数(另一个版本中用的是 .NET SDK 调用)删除 blob,自己没有 ShouldProcess;两者都看不到 -WhatIf。修复:每一处状态变更都放在 ShouldProcess 之后;再写一个 Pester 测试(第 8 课),带 -WhatIf 运行函数并断言没有任何变化——本课的故障注入实验做的正是同样的检查。

案例 2:每逢周一早上就“挂住”的定时任务

问题:一个每周清理任务从未结束。根因:清理函数的 ConfirmImpact = 'High';任务以 pwsh -File 运行且没有 -NonInteractive,于是一直等待一个没人能给出的确认。修复:加上 -NonInteractive(快速失败而不是挂起),并在任务命令行中显式写 -Confirm:$false——这是一个经过思考、可审查的决定。

案例 3:重跑导致数据翻倍

问题:一个中途失败的资源配置脚本被重跑后,创建了重复的 DNS 记录和用户。根因:“创建”步骤没有“已存在吗?”的检查。修复:幂等的步骤(先 Get,只在有差异时 Set)。OpsKit 的备份按名称幂等:同一个时间戳永远不会写两次(模块 8)。

常见错误与解决

A parameter cannot be found that matches parameter name 'WhatIf'

解决:在 [CmdletBinding()] 中加上 SupportsShouldProcess;函数必须是高级函数。

我的函数带 -WhatIf 时什么也不打印

原因:没有调用 ShouldProcess,内部也没有会继承首选项的 cmdlet——或者变更是通过 .NET / 原生 / 其他模块的代码完成的。解决:把变更包进 if ($PSCmdlet.ShouldProcess(…))。

Exception calling "ShouldProcess" … NonInteractive mode

原因:在非交互会话中需要确认。解决:有意识地传入 -Confirm:$false,或者如果命令的影响级别定得过高,就降低它。

-WhatIf 运行之后我的日志文件是空的

原因:Add-Content/Out-File 继承了 WhatIf。解决:日志写入加上 -WhatIf:$false,或像 Write-OpsLog 那样用 .NET 追加写入。

命令行练习
1. 预览删除 ~/pslab 下所有 *.tmp 文件,但不真正删除。
Get-ChildItem ~/pslab -Recurse -Filter *.tmp -File | Remove-Item -WhatIf
2. 写一个 High 影响级别函数的骨架,带一个跳过询问的 -Force 开关。
function Remove-OpsTenant {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param([Parameter(Mandatory)][string]$Name, [switch]$Force)
    if ($Force -and -not $PSBoundParameters.ContainsKey('Confirm')) { $ConfirmPreference = 'None' }
    if ($PSCmdlet.ShouldProcess($Name, 'Remove tenant')) { <# change #> }
}

已在 7.6.10 验证该模式:带 -Force 时函数不询问直接执行;-WhatIf 仍然优先,因为它最先被检查。

场景分析
团队想在所有部署脚本中用一个统一的 -DryRun 开关代替 -WhatIf,“因为 -WhatIf 不可靠”。你会怎么建议?

保留标准的 -WhatIf:运维人员和工具都认识它,内置 cmdlet 遵循它,它还能在管道中组合。它的“不可靠”是实现问题——用规则修复:每一处变更都在 ShouldProcess 中;调用其他模块的函数时显式传 -WhatIf:$WhatIfPreference;永远不要指望它传进 .NET 或原生调用;再写一个测试,对沙箱以 -WhatIf 运行每个脚本并断言状态没有变化。自定义的 -DryRun 需要同样的纪律,而且还得不到 cmdlet 自动继承这一好处。

经核实的教学视频

▶
Use PowerShell WhatIf So You Don't Break Stuff — Jeff Brown Tech
英文 · 为脚本和函数添加 -WhatIf
▶
Powershell Confirm, Impact and What-if — Tips For IT Pros
英文 · ConfirmImpact 与确认(较早的 Windows PowerShell)
▶
PowerShell ShouldProcess: Build WhatIf Into Your Own Scripts — AISLabs AI
英文 · 在你自己的高级函数中使用 ShouldProcess

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:函数中一个红色的“变更”框,由一道标着 ShouldProcess 的闸门守着。
讲解:每一处变更都要过这道闸门。
镜头 2 · 20–45 秒
画面:-WhatIf 把闸门变成打印 “What if:” 的打印机;Copy-Item 服从,Compress-Archive 绕过闸门创建了一个 zip。
讲解:cmdlet 继承 WhatIf;其他模块的函数可能不会。要验证。
镜头 3 · 45–70 秒
画面:一个刻度盘 ConfirmImpact Low/Medium/High 对着阈值 $ConfirmPreference;指针越过阈值时弹出询问。
讲解:影响级别与首选项的比较决定是否询问。
镜头 4 · 70–90 秒
画面:同一条命令运行两次;第二次亮起绿色的“已完成”。
讲解:先检查再变更,重跑才安全。
或测验得分 ≥ 70%

模块 7 · 重试、超时与结构化日志

42:00 – 50:00 · 瞬时故障值得一次有上限、带随机抖动的重试;慢的操作需要超时;每次运行都应留下机器可读的记录——每行一个 JSON 对象——而不是满屏的控制台文本
8 分钟Invoke-OpsRetry · JSON 行★★★★☆
学习目标
  • 实现 Invoke-OpsRetry:指数退避、“均等抖动”、上限,并且只重试列出的瞬时异常类型。
  • 解释为什么非终止错误永远不会被重试,以及为什么永久性错误不应该被重试。
  • 用 Wait-Job -Timeout、CancellationTokenSource 和 Web cmdlet 超时限制等待时间——并知道 -OperationTimeoutSeconds 没有截断迟迟不来的首个响应,而 -TimeoutSec 截断了(已验证)。
  • 用 ConvertTo-Json -Compress 写 JSON 行日志,用 ConvertFrom-Json 查询,并了解 Start-Transcript 的注意事项。
前置:模块 1–6。重要程度:★★★★☆

What:瞬时错误与永久错误

重试?示例原因
是(瞬时)文件被其他进程锁定(IOException)、超时(TimeoutException、TaskCanceledException)、HTTP 429/503、DNS 抖动稍后同样的调用可能成功
否(永久)文件不存在、拒绝访问、验证错误、HTTP 400/401/404、程序缺陷重试只会推迟并掩盖失败;涉及凭据时还可能锁定账户

Why:退避与抖动

在紧凑循环中立即重试会冲击一个本已吃力的服务。指数退避每次把等待时间翻倍(500 毫秒、1 秒、2 秒……)直到上限。抖动让每次等待随机化,这样同时失败的 200 个客户端不会同时重试。OpsKit 使用“均等抖动”:第 n 次重试前的延迟是 cap/2 到 cap 之间的随机值,其中 cap = min(MaxDelayMs, BaseDelayMs × 2^(n−1))。总时长一定要有上限:最大尝试次数,以及对外部调用的单次超时。

How:Invoke-OpsRetry 体现的规则

  • 只重试终止错误——所以脚本块里必须用 -ErrorAction Stop。非终止错误只是被写出,脚本块“成功”了(下文已验证)。
  • 用 -RetryOn 类型匹配异常及其内部异常(MethodInvocationException 这类包装器很常见)。
  • 在最后一次尝试或遇到不可重试的错误时,用 $PSCmdlet.ThrowTerminatingError() 重新抛出原始 ErrorRecord,这样调用者仍能按类型和 id 捕获。
  • 提供 -OnRetry 钩子,让调用者记录日志和清理(OpsKit 在其中删除不完整的归档,模块 8),并提供 -Seed 以便可复现地测试。

When:超时与日志

需求工具说明
限制一段 PowerShell 代码的时间Start-ThreadJob + Wait-Job -Timeout + Stop-Job超时时 Wait-Job 什么也不返回;作业会一直运行直到被停止
限制 .NET 异步调用[System.Threading.CancellationTokenSource]::new([TimeSpan])传入 .Token;捕获 TaskCanceledException / OperationCanceledException
限制 Web 调用Invoke-RestMethod -TimeoutSec(-ConnectionTimeoutSeconds 的别名)在 7.6.10 上,它在 2 秒后截断了一个迟迟不来的响应;-OperationTimeoutSeconds 没有(它管的是对进行中响应的读取)
机器可读的运行记录JSON 行:每个事件追加 [ordered]@{…} | ConvertTo-Json -Compress每行一个事件;只追加;grep/ConvertFrom-Json/任何日志采集器都能读
人可读的会话记录Start-Transcript注意:直接写到控制台的原生程序输出不会出现在记录中(已验证);可能记录到机密;每个会话一个
常见误解① “什么都重试三次”——重试永久错误会掩盖缺陷、推迟告警。② “我的重试包装能捕获 cmdlet 失败”——只有脚本块用了 -ErrorAction Stop 才行。③ “Wait-Job -Timeout 会杀掉作业”——它只是不再等待;要调用 Stop-Job。④ “-OperationTimeoutSeconds 是整个请求的超时”——在 7.6.10 上不是(值为 2 时,对一个迟迟不应答的服务器等了 5.2 秒)。⑤ “会话记录就是日志”——它是非结构化的文本转储,还漏掉原生控制台输出。⑥ “日志行应该是漂亮的 JSON”——每行一个紧凑对象,否则基于行的工具会出问题。

时间线:带均等抖动的退避(BaseDelayMs = 200,种子 42)

第 1 次 等待 167 毫秒区间 100–200 第 2 次 等待 228 毫秒区间 200–400 第 3 次 等待 450 毫秒区间 400–800 第 4 次 ✓ cap(n) = min(MaxDelayMs, Base × 2^(n−1));delay = cap/2 + random × cap/2 永久错误或尝试次数 = MaxAttempts → 重新抛出原始 ErrorRecord 7.6.10 实测:“succeeded on call 4”,耗时 ≈ 1.0 秒
图 5-9:等待时间指数增长,但每次都在各自区间内随机化,从而把大量客户端错开

图解:作为事件流的 JSON 行日志

Write-OpsLog[ordered]@{ ts; level;event; runId; … }ConvertTo-Json -CompressAppendAllText(不受 WhatIf 影响) {"ts":"…","level":"info","event":"backup.started",…}{"ts":"…","level":"warning","event":"backup.retry","attempt":1,…}{"ts":"…","level":"warning","event":"backup.retry","attempt":2,…}{"ts":"…","level":"info","event":"backup.created",…}每行一个对象 · 只追加 消费者ConvertFrom-Json | GroupSelect-String '"level":"error"'Fluent Bit / Azure MonitorLinux 上的 jq
图 5-10:带 runId 的结构化事件,让你能从众多运行中还原出某一次

重试时间线

选择脚本块的行为,观察 Invoke-OpsRetry 在每次尝试时如何决定。延迟是 7.6.10 实际运行的真实数值。

就绪。
动画对应的真实机制 Invoke-OpsRetry 在 try 中用 & 运行脚本块。终止错误落入 catch;函数遍历 $_.Exception 及其 InnerException 链,用 -is 逐一与 -RetryOn 比较,用 System.Random 计算带抖动的延迟,调用 -OnRetry 钩子,休眠后进入下一轮。非终止错误永远到不了 catch,所以循环在第一次尝试后就返回了。

命令表

命令用途说明
Invoke-OpsRetry -RetryOn ([System.IO.IOException]) { … -ErrorAction Stop }重试瞬时错误OpsKit v0.3;-MaxAttempts、-BaseDelayMs、-MaxDelayMs、-OnRetry、-Seed
Start-ThreadJob { … } | Wait-Job -Timeout 5有上限的等待之后 Stop-Job、Remove-Job
[Threading.CancellationTokenSource]::new([TimeSpan]::FromSeconds(5))取消 .NET 异步工作记得 Dispose
Invoke-RestMethod -TimeoutSec 10 -MaximumRetryCount 3 -RetryIntervalSec 2Web 超时与内置重试内置重试针对 HTTP 304/400–599 响应;见第 7 课
ConvertTo-Json -Compress -Depth 4单行 JSON嵌套数据务必设置 -Depth
Start-Transcript -Path f -UseMinimalHeader / Stop-Transcript会话文本记录不能代替结构化日志

Invoke-OpsRetry(OpsKit/Public/Invoke-OpsRetry.ps1)

function Invoke-OpsRetry {
    <#
    .SYNOPSIS
        Runs a script block and retries it on transient errors with exponential backoff and jitter.
    .DESCRIPTION
        Only terminating errors are retried, so use -ErrorAction Stop inside the script block.
        Delay before retry n = random value between cap/2 and cap, where
        cap = min(MaxDelayMs, BaseDelayMs * 2^(n-1))  ("equal jitter").
    .EXAMPLE
        Invoke-OpsRetry -RetryOn ([System.IO.IOException]) { Get-Content ./x.log -ErrorAction Stop }
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position = 0)][scriptblock]$ScriptBlock,
        [ValidateRange(1, 20)][int]$MaxAttempts = 3,
        [ValidateRange(0, 60000)][int]$BaseDelayMs = 500,
        [ValidateRange(0, 300000)][int]$MaxDelayMs = 10000,
        [type[]]$RetryOn = @([System.Exception]),
        [scriptblock]$OnRetry,
        [int]$Seed = -1
    )
    $random = if ($Seed -ge 0) { [System.Random]::new($Seed) } else { [System.Random]::new() }
    for ($attempt = 1; ; $attempt++) {
        try {
            return (& $ScriptBlock)
        }
        catch {
            $record = $_
            # Look through wrapper exceptions (MethodInvocationException, AggregateException ...).
            $chain = for ($e = $record.Exception; $e; $e = $e.InnerException) { $e }
            $transient = foreach ($e in $chain) { foreach ($t in $RetryOn) { if ($e -is $t) { $e } } }
            if (-not $transient -or $attempt -ge $MaxAttempts) {
                Write-Verbose ("attempt {0}/{1} failed, giving up: {2}" -f $attempt, $MaxAttempts, $record.Exception.Message)
                $PSCmdlet.ThrowTerminatingError($record)
            }
            $cap   = [math]::Min($MaxDelayMs, $BaseDelayMs * [math]::Pow(2, $attempt - 1))
            $delay = [int]($cap / 2 + $random.NextDouble() * $cap / 2)
            Write-Verbose ("attempt {0}/{1} failed ({2}); retrying in {3} ms" -f $attempt, $MaxAttempts, @($transient)[0].GetType().Name, $delay)
            if ($OnRetry) { & $OnRetry $attempt $delay $record }
            Start-Sleep -Milliseconds $delay
        }
    }
}

瞬时错误:重试后成功

Import-Module ./OpsKit/OpsKit.psd1 -Force
$script:calls = 0
$sw = [System.Diagnostics.Stopwatch]::StartNew()
Invoke-OpsRetry -MaxAttempts 5 -BaseDelayMs 200 -Seed 42 -RetryOn ([System.TimeoutException]) -Verbose {
    $script:calls++
    if ($script:calls -lt 4) { throw [System.TimeoutException]::new("call $script:calls timed out") }
    "succeeded on call $script:calls"
}
"elapsed ~{0:N1} s" -f $sw.Elapsed.TotalSeconds
VERBOSE: attempt 1/5 failed (TimeoutException); retrying in 167 ms
VERBOSE: attempt 2/5 failed (TimeoutException); retrying in 228 ms
VERBOSE: attempt 3/5 failed (TimeoutException); retrying in 450 ms
succeeded on call 4
elapsed ~1.0 s

如何验证:每个延迟都落在各自区间内(100–200、200–400、400–800 毫秒)。常见错误:忘了“耗时”还包括工作本身——外部调用要设置单次超时。生产用法:只重试你在日志中见过确实是瞬时的类型。

永久错误和非终止错误不会被重试

try {
    Invoke-OpsRetry -MaxAttempts 5 -RetryOn ([System.TimeoutException]) -Verbose {
        Get-Item ./data/nope.txt -ErrorAction Stop
    }
} catch { "not retried, caught: $($_.Exception.GetType().Name)" }

Invoke-OpsRetry -MaxAttempts 3 -BaseDelayMs 100 -Verbose { Get-Item ./data/nope.txt }
'non-terminating error: no retry happened, and the caller continues'
VERBOSE: attempt 1/5 failed, giving up: Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist.
not retried, caught: ItemNotFoundException
Get-Item: Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist.
non-terminating error: no retry happened, and the caller continues

超时

$job = Start-ThreadJob { Start-Sleep -Seconds 10; 'finished' }
$done = $job | Wait-Job -Timeout 2
if (-not $done) {
    "timed out after 2 s; state = $($job.State)"
    $job | Stop-Job
    "after Stop-Job: $($job.State)"
}
$job | Remove-Job

$cts = [System.Threading.CancellationTokenSource]::new([TimeSpan]::FromMilliseconds(500))
try {
    [System.Threading.Tasks.Task]::Delay(5000, $cts.Token).GetAwaiter().GetResult()
}
catch [System.Threading.Tasks.TaskCanceledException] {
    "cancelled after 500 ms: $($_.Exception.GetType().Name)"
}
finally { $cts.Dispose() }
timed out after 2 s; state = Running
after Stop-Job: Stopped
cancelled after 500 ms: TaskCanceledException

对一个缓慢的本地模拟 API 设置 Web 超时

# Mock API on localhost: every request is answered after 5 seconds
$server = Start-ThreadJob {
    $l = [System.Net.HttpListener]::new(); $l.Prefixes.Add('http://localhost:8765/'); $l.Start()
    1..2 | ForEach-Object { $ctx = $l.GetContext(); Start-Sleep -Seconds 5; $ctx.Response.Close() }
    $l.Stop()
}
Start-Sleep -Milliseconds 800
foreach ($opt in @{ OperationTimeoutSeconds = 2 }, @{ TimeoutSec = 2 }) {
    $sw = [System.Diagnostics.Stopwatch]::StartNew()
    try {
        $null = Invoke-RestMethod http://localhost:8765/slow @opt
        "{0,-26} returned after {1:N1} s" -f "-$($opt.Keys)", $sw.Elapsed.TotalSeconds
    }
    catch {
        "{0,-26} {1} after {2:N1} s" -f "-$($opt.Keys)", $_.Exception.GetType().Name, $sw.Elapsed.TotalSeconds
    }
}
$server | Wait-Job -Timeout 15 | Remove-Job
-OperationTimeoutSeconds   returned after 5.2 s
-TimeoutSec                TaskCanceledException after 2.0 s

第二次调用的异常消息是 The request was canceled due to the configured HttpClient.Timeout of 2 seconds elapsing.。这里使用 localhost,是因为在 Windows 上 http://127.0.0.1:… 形式的 HttpListener 前缀可能需要 URL 保留。

结构化日志:Write-OpsLog(OpsKit/Private/Write-OpsLog.ps1)

function Write-OpsLog {
    # Appends one JSON object per line (JSON Lines) to $Path. Never throws: logging must not
    # turn a successful operation into a failure, so a log write error becomes a warning.
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Path,
        [Parameter(Mandatory)][ValidateSet('debug', 'info', 'warning', 'error')][string]$Level,
        [Parameter(Mandatory)][string]$Event,
        [hashtable]$Data = @{},
        [string]$RunId = ''
    )
    $record = [ordered]@{
        ts    = [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ss.fffZ')
        level = $Level
        event = $Event
        runId = $RunId
    }
    foreach ($key in $Data.Keys | Sort-Object) { $record[$key] = $Data[$key] }
    $Path = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)   # .NET resolves relative paths against the process folder, not $PWD
    $line = ($record | ConvertTo-Json -Compress -Depth 4) + "`n"
    try {
        $dir = Split-Path -Parent $Path
        if (-not [System.IO.Directory]::Exists($dir)) { $null = [System.IO.Directory]::CreateDirectory($dir) }
        # .NET API on purpose: Add-Content would honour -WhatIf and silently skip the log line.
        [System.IO.File]::AppendAllText($Path, $line, [System.Text.UTF8Encoding]::new($false))
    }
    catch {
        Write-Warning "OpsKit: could not write log ${Path}: $($_.Exception.Message)"
    }
}

设计取舍:带毫秒的 UTC ISO-8601 时间戳;用于归组事件的短 runId;额外键排序以便稳定比对;用 .NET 追加写入,使 -WhatIf 运行也有日志(模块 6);日志函数永不抛出异常。

Start-Transcript 的注意事项

# ./scripts/Show-Transcript.ps1
Start-Transcript -Path ./tmp/transcript.txt -UseMinimalHeader | Out-Null
'success output'
Write-Host 'host output'
Write-Verbose 'verbose (not enabled)'
cmd /c echo native-output
Stop-Transcript | Out-Null
pwsh -NoProfile -File ./scripts/Show-Transcript.ps1
'--- transcript file:'
Get-Content ./tmp/transcript.txt
success output
host output
native-output
--- transcript file:
**********************
PowerShell transcript start
Start time: 20261124210504
**********************
success output
host output

**********************
PowerShell transcript end
End time: 20261124210504
**********************

控制台显示了 native-output;会话记录中对应位置只有一个空行。如果原生输出必须被记录,就让它经过 PowerShell(cmd /c echo x | Out-Host,或先捕获再输出)。

目标:在一个真实的瞬时故障上使用 Invoke-OpsRetry 和 Write-OpsLog 风格的事件。环境:~/pslab,OpsKit 0.3.0。成本:无。

让一个文件暂时无法读取,并带重试地读取它:
Import-Module ./OpsKit/OpsKit.psd1 -Force
$p = (Resolve-Path ./data/servers.csv).Path
$lock = Start-ThreadJob -ArgumentList $p { param($p) $fs = [IO.File]::Open($p, 'Open', 'Read', 'None'); Start-Sleep -Milliseconds 900; $fs.Dispose() }
Start-Sleep -Milliseconds 200
Invoke-OpsRetry -MaxAttempts 5 -BaseDelayMs 300 -RetryOn ([System.IO.IOException]) -Verbose {
    (Import-Csv -LiteralPath $p -ErrorAction Stop).Count
}
$lock | Wait-Job | Remove-Job
VERBOSE: attempt 1/5 failed (IOException); retrying in 165 ms
VERBOSE: attempt 2/5 failed (IOException); retrying in 566 ms
VERBOSE: attempt 3/5 failed (IOException); retrying in 624 ms
12

如果没有看到重试,说明锁在第一次读取前就释放了——增加线程作业中的休眠时间。

记录你自己的事件(私有的 Write-OpsLog 没有导出,所以借助模块作用域调用它——适合实验,不适合生产代码):
& (Get-Module OpsKit) { Write-OpsLog -Path ./tmp/lab.jsonl -Level info -Event 'lab.test' -Data @{ answer = 42 } }
Get-Content ./tmp/lab.jsonl | ConvertFrom-Json | Format-Table ts, level, event, answer
ts                    level event    answer
--                    ----- -----    ------
11/25/2026 2:29:33 AM info  lab.test     42

编写本实验时发现的一个真实缺陷:Write-OpsLog 的第一版把 ./tmp/lab.jsonl 直接传给 [IO.File]::AppendAllText,而它是相对于进程工作目录([Environment]::CurrentDirectory)而不是 PowerShell 的 $PWD 解析相对路径的——日志写到了别处,Get-Content 报 Cannot find path。修复就是那行 GetUnresolvedProviderPathFromPSPath()。规则:把任何路径交给 .NET 之前,先转换成完整的提供程序路径。

为一段慢代码设置超时:把 Start-Sleep 10 放进线程作业,像“命令”分页那样在 2 秒后停止它。
清理:Remove-Item ./tmp/lab.jsonl, ./tmp/transcript.txt -ErrorAction Ignore

案例 1:重试风暴

问题:一次 30 秒的数据库故障转移之后,400 个工作脚本每秒重试一次且没有抖动,让数据库 CPU 在 100% 持续了 20 分钟。根因:固定间隔、无抖动、无尝试次数上限。修复:带抖动和上限的指数退避;对长时间中断,在调用方加断路器。

案例 2:锁定了服务账户的重试

问题:一个同步作业每次运行对失败的登录重试 5 次,每 5 分钟运行一次。目录服务锁定了该账户。根因:不分类型的 catch { retry }——身份验证失败是永久错误。修复:-RetryOn 只列网络/超时类型;身份验证错误带清晰的 id 立即失败。

案例 3:“是哪次运行删了那个文件?”

问题:几次重叠的运行写出交错的文本日志;没人能看出是哪次运行删除了某个备份。根因:没有运行标识的自由文本日志。修复:带 runId、event 和受影响文件的 JSON 行(OpsKit 的 backup.removed 事件)——这样 Get-Content log | ConvertFrom-Json | Where-Object event -eq 'backup.removed' 一行就能回答。

常见错误与解决

我的重试包装从不重试

原因:脚本块中的错误是非终止的,或者异常类型(及其内部异常)不在 -RetryOn 中。

try { <block> } catch { $e = $_.Exception; while ($e) { $e.GetType().FullName; $e = $e.InnerException } }
ConvertTo-Json 的输出被截断成 "System.Collections.Hashtable"

原因:默认 -Depth 为 2;更深的层级用 ToString() 转换。

@{ a = @{ b = @{ c = @{ d = 1 } } } } | ConvertTo-Json -Compress
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{"a":{"b":{"c":"System.Collections.Hashtable"}}}

解决:-Depth 4 或更大。

我的日志文件不在我指定的位置

原因:传给 .NET 方法的相对路径是相对于 [Environment]::CurrentDirectory 解析的,而 Set-Location 不会改变它。解决:先用 $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) 或 Join-Path $PWD …(见“实验”分页)。

Wait-Job -Timeout 返回了,但工作还在运行

解决:Stop-Job,然后 Remove-Job;对于线程作业,尽可能让工作本身可取消。

The request was canceled due to the configured HttpClient.Timeout

原因:-TimeoutSec 已到。解决:判断这是瞬时的(带退避重试),还是端点本来就慢(调大超时)。

命令行练习
1. 统计 ~/pslab/backups/opskit-backup.jsonl 中各级别的事件数量。
Get-Content ~/pslab/backups/opskit-backup.jsonl | ConvertFrom-Json | Group-Object level -NoElement
2. 计算 BaseDelayMs 500、MaxDelayMs 3000 时的四个延迟区间。
1..4 | ForEach-Object { $cap = [math]::Min(3000, 500 * [math]::Pow(2, $_ - 1)); '{0}: {1}-{2} ms' -f $_, ($cap / 2), $cap }

1:250–500,2:500–1000,3:1000–2000,4:1500–3000(受上限约束)。

场景分析
某个 API 有时需要 90 秒才应答,有时根本不应答。你的脚本在 3 次重试中调用它,没有设置超时。计算最坏情况并重新设计。

没有超时时,一次永不应答的调用会一直阻塞(或直到 HttpClient 默认的 100 秒,然后重试重新开始):最坏约 3 × 100 秒加退避——大约 5 分钟,若有其他客户端影响则可能无限期。重新设计:单次 -TimeoutSec 略高于正常的 p99(如果 90 秒是正常的,就设 120 秒),只对超时/5xx/429 重试,最多 3 次并带抖动退避,并在每次尝试前检查整体截止时间(剩余时间不足一次超时就停止)。把每次尝试连同耗时记录为一个事件。

经核实的教学视频

没有找到讲 PowerShell 重试/退避模式或 JSON 行日志的经核实视频。请以本模块和官方文档为准。

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:200 个客户端同时失败,又齐步重试;一个服务器图标变红。
讲解:没有抖动的重试会把一次抖动变成一次故障。
镜头 2 · 20–45 秒
画面:重试时间线上,等待条不断变长且随机化。
讲解:指数退避、随机化,几次之后就停。
镜头 3 · 45–65 秒
画面:两个错误来到闸门前:“文件被锁”进入重试循环,“找不到”被直接送出。
讲解:只重试瞬时错误。
镜头 4 · 65–90 秒
画面:一堵控制台文字墙坍缩成带 runId 的整齐 JSON 行;一条查询挑出某一次运行。
讲解:记录事件,而不是散文。
或测验得分 ≥ 70%

模块 8 · OpsKit v0.3:带轮转、-WhatIf、重试与日志的 Invoke-OpsBackup

50:00 – 60:00 · 模块 1–7 的全部内容汇集到一个命令中:守卫语句、带稳定 id 的类型化错误、包住每处变更的 ShouldProcess、对被锁文件重试并清理不完整归档、继承 -WhatIf 的轮转、JSON 行日志——以及一个退出码说真话的夜间包装脚本
10 分钟OpsKit 0.3.0★★★★★
学习目标
  • 阅读并运行 Invoke-OpsBackup 和 Remove-OpsBackup;复现它们在 -WhatIf、-Verbose、幂等重跑、轮转和重试下的行为。
  • 解释不完整归档陷阱:不带 Stop 的 Compress-Archive 写出了一个 15 个条目的 zip,而 $? 为 $true(已验证)。
  • 把模块命令包装成对调度器友好的脚本:在边界处 Stop,并使用不同的退出码(0–4)。
  • 用排错决策树诊断“错误没有被捕获”和“脚本报告成功但实际失败”。
前置:模块 1–7;第 4 课的 OpsKit v0.2。重要程度:★★★★★

What:v0.3 的命令

命令功能安全特性
Invoke-OpsBackup把 ~/pslab/data 的顶层项(排除 Backup.Exclude 模式)压缩到 ~/pslab/backups/pslab-data-yyyyMMdd-HHmmss.zip,然后轮转带 id OpsKit.BackupSourceNotFound 的守卫语句;按名称幂等(已有归档永不覆盖:警告 + 状态 Exists);唯一的写操作被 ShouldProcess 包住;通过 Invoke-OpsRetry 重试 IOException;每次尝试失败后删除不完整归档;JSON 行事件 backup.started/retry/created/failed;返回一个结果对象
Remove-OpsBackup保留最新的 -Keep 份归档(配置 Backup.Keep = 7),删除其余只匹配 pslab-data-*.zip;[ValidateRange(1,365)] 使 -Keep 0 不可能;每个文件一次 ShouldProcess;事件 backup.removed
Invoke-OpsRetry通用重试(模块 7)只重试列出的类型;重新抛出原始错误
scripts/Invoke-NightlyBackup.ps1调度器入口严格模式、Stop、原生命令首选项开启;打开归档进行验证;退出码 0 成功 · 1 备份失败 · 2 缺少配置 · 3 缺少源目录 · 4 归档无效;stderr 上一行便于 grep 的消息

Why:每个设计决定都对应一起事故

决定防止什么模块
在重试中使用 Compress-Archive … -ErrorAction Stop一个“成功”的备份悄悄缺了被锁的文件——下文复现:16 个条目只有 15 个,$? = True1、2
在 -OnRetry 和 catch 中删除不完整归档重试因“文件已存在”失败,或留下一个损坏的 zip 让下次运行“幂等地”跳过7
用自己的 ShouldProcess 包住 Compress-Archive在 -WhatIf 时创建归档(已验证:-WhatIf 传不到 Compress-Archive)6
带稳定 id 的 ThrowTerminatingError调用者匹配英文消息;错误看起来来自 OpsKit 内部某一行2
包装脚本中的 Stop + try/catch + exit N“脚本报告成功”——下文用一个简陋的包装脚本复现:打印了错误,exit=01、2、3
$env:OPSKIT_HOME测试碰到真实备份0、综合实验

How:执行路径

  1. 读取配置;解析 Source、Destination、Keep、LogPath(参数优先于配置)。
  2. 守卫:源目录必须存在,否则记录 backup.failed 并 ThrowTerminatingError。
  3. 由 -Timestamp(默认当前时间)计算归档名。已存在 → 警告,状态 Exists(幂等)。
  4. ShouldProcess → 若 -WhatIf,状态 WhatIf,不写任何东西。
  5. 压缩,遇 IOException 重试;每次失败后记录 backup.retry 并删除不完整 zip。
  6. 记录带大小和尝试次数的 backup.created;最终失败时记录 backup.failed、清理并重新抛出。
  7. 用 Remove-OpsBackup 轮转——因为在同一模块中,它会继承 -WhatIf/-Confirm。
  8. 返回 [pscustomobject]@{ Archive; Items; SizeKB; Attempts; Removed; RunId; Status }。

When:怎么运行它?

  • 交互式:先 Invoke-OpsBackup -WhatIf,再去掉它。
  • 定时:pwsh -NoProfile -NonInteractive -File ~/pslab/scripts/Invoke-NightlyBackup.ps1(任务计划程序、cron、CI 定时)。对非零退出码告警;细节看 JSON 日志。
  • 设计上的已知局限:-WhatIf 预览轮转时不包含它本会创建的那个归档,所以比真实运行少显示一次删除(已验证:2 对 3)。诚实的预览需要代码把待发生的变更考虑进去——这是一个不错的练习。
常见误解① “文件被锁时 Compress-Archive 会失败”——不带 Stop 时它只写一个错误并留下不完整归档;$? 仍为 $true(已验证)。② “模块抛出了错误,所以我的脚本会停”——ThrowTerminatingError 是语句终止的;一个简陋的包装脚本打印了 “Backup finished” 并以 0 退出(已验证)。③ “按 LastWriteTime 轮转更安全”——文件被复制时时间戳会变;这里可排序的文件名才是依据。④ “日志写入失败可能让备份失败”——Write-OpsLog 从不抛出;日志失败只变成一条警告。⑤ “名字对的现有归档就是好归档”——包装脚本会验证它(综合实验中损坏的归档 → exit 4)。

流程图:Invoke-OpsBackup

Get-OpsConfigConfigNotFound → exit 2 源目录存在?否 → SourceNotFound(3) 归档已存在?是 → 警告,Exists ShouldProcess-WhatIf → WhatIf Invoke-OpsRetry -RetryOn IOExceptionCompress-Archive -LiteralPath items -ErrorAction StopOnRetry:记录 backup.retry,删除不完整 zip放弃 → 记录 backup.failed,删除,重新抛出(exit 1) backup.createdsizeKB · attempts Remove-OpsBackup -Keep 7继承 -WhatIf · backup.removed 结果对象Archive · Items · SizeKB · Attempts · Removed · RunId · Status Invoke-NightlyBackup.ps1:Strict + Stop + 原生首选项 · try { Invoke-OpsBackup; 验证 zip } catch { id → 退出码 }0 成功 · 1 备份失败 · 2 缺少配置 · 3 缺少源目录 · 4 归档无效——给调度器的一行 stderr
图 5-11:每个可能失败的箭头都有一个命名的结果——日志中的一个事件和一个独立的退出码

备份执行路径

选择一种情况,逐步跟随 Invoke-OpsBackup(以及夜间包装脚本)的执行。下方是交互式排错决策树。

就绪。

交互式排错决策树:错误没有被捕获 / 脚本报告成功但实际失败

命令表

命令用途说明
Invoke-OpsBackup -WhatIf预览显示归档以及轮转要删除的文件
Invoke-OpsBackup -Timestamp '2026-11-24 10:00:00'确定性的文件名所有示例都使用它;生产中使用默认值(当前时间)
Invoke-OpsBackup -Keep 30 -MaxAttempts 4 -BaseDelayMs 200覆盖配置 / 重试参数有范围验证
Remove-OpsBackup -Keep 7 -WhatIf只做轮转Keep 默认取自配置
Get-Content ~/pslab/backups/opskit-backup.jsonl | ConvertFrom-Json读取日志按 event 分组,按 runId 过滤
pwsh -NoProfile -NonInteractive -File ./scripts/Invoke-NightlyBackup.ps1定时运行检查 $LASTEXITCODE

OpsKit/Public/Invoke-OpsBackup.ps1

function Invoke-OpsBackup {
    <#
    .SYNOPSIS
        Zips ~/pslab/data into ~/pslab/backups, keeps the newest N archives and logs as JSON lines.
    .DESCRIPTION
        Settings come from opskit.config.psd1 (Backup.Destination, Backup.Keep, Backup.Exclude);
        parameters override them. Supports -WhatIf / -Confirm, which also reach the rotation step.
        Locked files (IOException) are retried with exponential backoff.
    .EXAMPLE
        Invoke-OpsBackup -WhatIf
    .EXAMPLE
        Invoke-OpsBackup -Timestamp '2026-11-24 10:00:00' -Verbose
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    [OutputType([pscustomobject])]
    param(
        [string]$Source,
        [string]$Destination,
        [ValidateRange(1, 365)][int]$Keep,
        [datetime]$Timestamp = (Get-Date),
        [ValidateRange(1, 10)][int]$MaxAttempts = 3,
        [ValidateRange(0, 60000)][int]$BaseDelayMs = 500,
        [string]$LogPath
    )
    $cfg = Get-OpsConfig
    if (-not $Source)      { $Source = Resolve-OpsPath '~/pslab/data' }
    if (-not $Destination) { $Destination = Resolve-OpsPath $cfg.Backup.Destination }
    if (-not $PSBoundParameters.ContainsKey('Keep')) { $Keep = $cfg.Backup.Keep }
    if (-not $LogPath)     { $LogPath = Join-Path $Destination 'opskit-backup.jsonl' }
    $runId = [guid]::NewGuid().ToString('n').Substring(0, 8)
    $log = @{ Path = $LogPath; RunId = $runId }

    # Guard clause: fail fast, with a specific error id the caller can test.
    if (-not (Test-Path -LiteralPath $Source -PathType Container)) {
        Write-OpsLog @log -Level error -Event 'backup.failed' -Data @{ reason = 'SourceNotFound'; source = $Source }
        $PSCmdlet.ThrowTerminatingError([System.Management.Automation.ErrorRecord]::new(
            [System.IO.DirectoryNotFoundException]::new("Backup source not found: $Source"),
            'OpsKit.BackupSourceNotFound', [System.Management.Automation.ErrorCategory]::ObjectNotFound, $Source))
    }

    $zip   = Join-Path $Destination ('pslab-data-{0:yyyyMMdd-HHmmss}.zip' -f $Timestamp)
    $items = @(Get-ChildItem -LiteralPath $Source -Force | Where-Object {
        $name = $_.Name
        -not ($cfg.Backup.Exclude | Where-Object { $name -like $_ })
    })
    $result = [pscustomobject]@{
        Archive = $zip; Items = $items.Count; SizeKB = $null; Attempts = 0; Removed = 0; RunId = $runId; Status = 'Skipped'
    }

    if (Test-Path -LiteralPath $zip) {
        # Idempotent: the same timestamp was already backed up; do not overwrite it.
        Write-Warning "Backup already exists, nothing to do: $zip"
        $result.Status = 'Exists'
    }
    elseif ($PSCmdlet.ShouldProcess($zip, "Create backup of $Source ($($items.Count) items)")) {
        Write-OpsLog @log -Level info -Event 'backup.started' -Data @{ source = $Source; archive = $zip; items = $items.Count }
        try {
            if (-not (Test-Path -LiteralPath $Destination)) { $null = New-Item -ItemType Directory -Path $Destination }
            Invoke-OpsRetry -MaxAttempts $MaxAttempts -BaseDelayMs $BaseDelayMs -RetryOn ([System.IO.IOException]) -OnRetry {
                param($attempt, $delay, $err)
                $result.Attempts = $attempt
                Write-OpsLog @log -Level warning -Event 'backup.retry' -Data @{ attempt = $attempt; delayMs = $delay; error = $err.Exception.Message }
                # Compress-Archive may leave a partial archive behind; never retry on top of it.
                if (Test-Path -LiteralPath $zip) { Remove-Item -LiteralPath $zip -WhatIf:$false }
            } -ScriptBlock {
                Compress-Archive -LiteralPath $items.FullName -DestinationPath $zip -ErrorAction Stop
            }
            $result.Attempts++
            $result.SizeKB = [math]::Round((Get-Item -LiteralPath $zip).Length / 1KB, 1)
            $result.Status = 'Created'
            Write-OpsLog @log -Level info -Event 'backup.created' -Data @{ archive = $zip; sizeKB = $result.SizeKB; attempts = $result.Attempts }
        }
        catch {
            Write-OpsLog @log -Level error -Event 'backup.failed' -Data @{ reason = $_.FullyQualifiedErrorId; error = $_.Exception.Message }
            if (Test-Path -LiteralPath $zip) { Remove-Item -LiteralPath $zip -WhatIf:$false }
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
    else {
        $result.Status = 'WhatIf'
    }

    # Rotation inherits -WhatIf / -Confirm automatically (same module, same call chain).
    $removed = @(Remove-OpsBackup -Destination $Destination -Keep $Keep -LogPath $LogPath -RunId $runId)
    $result.Removed = $removed.Count
    $result
}

OpsKit/Public/Remove-OpsBackup.ps1

function Remove-OpsBackup {
    <#
    .SYNOPSIS
        Deletes old backup archives, keeping the newest -Keep files.
    .EXAMPLE
        Remove-OpsBackup -Keep 7 -WhatIf
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    [OutputType([System.IO.FileInfo])]
    param(
        [ValidateRange(1, 365)][int]$Keep,
        [string]$Destination,
        [string]$LogPath,
        [string]$RunId = ([guid]::NewGuid().ToString('n').Substring(0, 8))
    )
    $cfg = Get-OpsConfig
    if (-not $PSBoundParameters.ContainsKey('Keep')) { $Keep = $cfg.Backup.Keep }
    if (-not $Destination) { $Destination = Resolve-OpsPath $cfg.Backup.Destination }
    if (-not $LogPath)     { $LogPath = Join-Path $Destination 'opskit-backup.jsonl' }
    if (-not (Test-Path -LiteralPath $Destination -PathType Container)) {
        Write-Verbose "no backup folder yet: $Destination"
        return
    }
    # The name embeds the timestamp (yyyyMMdd-HHmmss), so a name sort is a time sort.
    $old = Get-ChildItem -LiteralPath $Destination -Filter 'pslab-data-*.zip' -File |
        Sort-Object Name -Descending |
        Select-Object -Skip $Keep
    foreach ($file in $old) {
        if ($PSCmdlet.ShouldProcess($file.Name, 'Remove old backup')) {
            Remove-Item -LiteralPath $file.FullName
            Write-OpsLog -Path $LogPath -Level info -Event 'backup.removed' -RunId $RunId -Data @{ file = $file.Name }
            $file
        }
    }
}

OpsKit/Public/Get-OpsConfig.ps1(修改)与 OpsKit/Private/Resolve-OpsPath.ps1(新增)

function Get-OpsConfig {
    <#
    .SYNOPSIS
        Reads opskit.config.psd1 safely (no code execution).
    #>
    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [string]$Path = (Resolve-OpsPath '~/pslab/data/opskit.config.psd1')
    )
    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
        $err = [System.Management.Automation.ErrorRecord]::new(
            [System.IO.FileNotFoundException]::new("OpsKit config not found: $Path", $Path),
            'OpsKit.ConfigNotFound',
            [System.Management.Automation.ErrorCategory]::ObjectNotFound,
            $Path)
        $PSCmdlet.ThrowTerminatingError($err)
    }
    Import-PowerShellDataFile -LiteralPath $Path
}
function Resolve-OpsPath {
    # Maps '~/pslab/...' (as written in opskit.config.psd1) to the OpsKit root.
    # The root is $env:OPSKIT_HOME when set (tests, CI), otherwise ~/pslab.
    [CmdletBinding()]
    [OutputType([string])]
    param([Parameter(Mandatory)][string]$Path)

    $root = if ($env:OPSKIT_HOME) { $env:OPSKIT_HOME } else { Join-Path $HOME 'pslab' }
    if ($Path -match '^~[\\/]pslab(?<rest>([\\/].*)?)$') {
        $rest = $Matches.rest.TrimStart('\', '/')
        if ($rest) { return (Join-Path $root $rest) } else { return $root }
    }
    $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
}

OpsKit.psm1 与 OpsKit.psd1

# OpsKit.psm1 - loads Private helpers first, then Public commands, and exports only Public ones.
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'          # module scope only; callers are not affected

$private = @(Get-ChildItem -Path (Join-Path $PSScriptRoot 'Private') -Filter '*.ps1' -File)
$public  = @(Get-ChildItem -Path (Join-Path $PSScriptRoot 'Public')  -Filter '*.ps1' -File)
foreach ($file in $private + $public) {
    . $file.FullName
}
Export-ModuleMember -Function $public.BaseName
@{
    RootModule           = 'OpsKit.psm1'
    ModuleVersion        = '0.3.0'
    GUID                 = '4f6f2d8e-5b1c-4b8a-9a43-0c1d2e3f4a5b'
    Author               = 'pslab'
    Description          = 'OpsKit: operations helpers built during the PowerShell course.'
    PowerShellVersion    = '7.4'
    CompatiblePSEditions = @('Core')
    FunctionsToExport    = @(
        'Get-OpsConfig', 'Get-OpsServer', 'Test-OpsEndpoint',          # v0.1 / v0.2
        'Invoke-OpsRetry', 'Invoke-OpsBackup', 'Remove-OpsBackup'      # new in v0.3
    )
    CmdletsToExport      = @()
    VariablesToExport    = @()
    AliasesToExport      = @()
    PrivateData          = @{ PSData = @{ ReleaseNotes = '0.3.0: Invoke-OpsBackup, Remove-OpsBackup, Invoke-OpsRetry, JSON-lines log.' } }
}

促成 -ErrorAction Stop 的陷阱:不完整归档与 $? = True

$fs = [IO.File]::Open((Resolve-Path ./data/access.log).Path, 'Open', 'Read', 'None')   # simulate a log shipper
Compress-Archive -LiteralPath (Get-ChildItem ./data -Force).FullName -DestinationPath ./tmp/locked2.zip
"after (no -EA Stop): $?  exists=$(Test-Path ./tmp/locked2.zip)"
$fs.Dispose()
Add-Type -AssemblyName System.IO.Compression.FileSystem
$z = [IO.Compression.ZipFile]::OpenRead((Resolve-Path ./tmp/locked2.zip).Path)
"entries: $($z.Entries.Count)"; ($z.Entries | Where-Object FullName -notlike 'files/*').FullName -join ', '
$z.Dispose()
Write-Error: The process cannot access the file 'C:\Users\labadmin\pslab\data\access.log' because it is being used by another process.
after (no -EA Stop): True  exists=True
entries: 15
inventory.json, opskit.config.psd1, servers.csv

完整的归档有 16 个条目(4 个顶层文件 + files/ 中的 12 个,包括 [draft] notes.md 和 a&b;c.txt——-LiteralPath 正确处理了所有奇怪的文件名)。这里缺少 access.log,zip 却存在且 $? 为 True,因为错误来自脚本模块函数内部的 Write-Error。加上 -ErrorAction Stop 后,同样的调用抛出 System.IO.IOException(id 为 CompressArchiveUnauthorizedAccessError,ZipArchiveHelper),并且没有留下归档。

预览、运行、重跑

Import-Module ./OpsKit/OpsKit.psd1 -Force
Invoke-OpsBackup -Timestamp '2026-11-24 10:00:00' -WhatIf | Format-Table Status, Items, Attempts, Removed -AutoSize
Test-Path ./backups/pslab-data-20261124-100000.zip
# then:
Invoke-OpsBackup -Timestamp '2026-11-24 10:00:00' -Verbose | Format-Table Status, Items, SizeKB, Attempts, Removed, RunId -AutoSize
Invoke-OpsBackup -Timestamp '2026-11-24 10:00:00' | Format-Table Status, Items, SizeKB, Attempts, Removed -AutoSize
What if: Performing the operation "Create backup of C:\Users\labadmin\pslab\data (5 items)" on target "C:\Users\labadmin\pslab\backups\pslab-data-20261124-100000.zip".

Status Items Attempts Removed
------ ----- -------- -------
WhatIf     5        0       0

False
VERBOSE: Performing the operation "Create backup of C:\Users\labadmin\pslab\data (5 items)" on target "C:\Users\labadmin\pslab\backups\pslab-data-20261124-100000.zip".

Status  Items SizeKB Attempts Removed RunId
------  ----- ------ -------- ------- -----
Created     5   8.00        1       0 b3965fc4

WARNING: Backup already exists, nothing to do: C:\Users\labadmin\pslab\backups\pslab-data-20261124-100000.zip

Status Items SizeKB Attempts Removed
------ ----- ------ -------- -------
Exists     5               0       0

先 -WhatIf 再真实执行轮转

# simulate eight earlier nightly runs (Nov 16 ... Nov 23); -Keep 30 so nothing is rotated yet
16..23 | ForEach-Object { $null = Invoke-OpsBackup -Timestamp ([datetime]"2026-11-$_ 02:00:00") -Keep 30 }
(Get-ChildItem ./backups -Filter *.zip).Count
Invoke-OpsBackup -Timestamp '2026-11-25 02:00:00' -WhatIf | Format-Table Status, Removed -AutoSize
Invoke-OpsBackup -Timestamp '2026-11-25 02:00:00' | Format-Table Status, Items, SizeKB, Attempts, Removed -AutoSize
(Get-ChildItem ./backups -Filter *.zip).Name
9
What if: Performing the operation "Create backup of C:\Users\labadmin\pslab\data (5 items)" on target "C:\Users\labadmin\pslab\backups\pslab-data-20261125-020000.zip".
What if: Performing the operation "Remove old backup" on target "pslab-data-20261117-020000.zip".
What if: Performing the operation "Remove old backup" on target "pslab-data-20261116-020000.zip".

Status Removed
------ -------
WhatIf       0


Status  Items SizeKB Attempts Removed
------  ----- ------ -------- -------
Created     5   8.00        1       3

pslab-data-20261119-020000.zip
pslab-data-20261120-020000.zip
pslab-data-20261121-020000.zip
pslab-data-20261122-020000.zip
pslab-data-20261123-020000.zip
pslab-data-20261124-100000.zip
pslab-data-20261125-020000.zip

预览列出两次删除;真实运行删除了三份(16 日、17 日以及 18 日),因为新归档也计入了那 7 份。这就是文档中说明的预览局限。

文件被锁:重试后成功

# Hold an exclusive lock on access.log for 1.2 seconds in a background thread (simulates a log shipper)
$logFile = Join-Path $PWD 'data/access.log'
$lock = Start-ThreadJob {
    $fs = [System.IO.File]::Open($using:logFile, 'Open', 'Read', 'None')
    Start-Sleep -Milliseconds 1200; $fs.Dispose()
}
Start-Sleep -Milliseconds 200
Invoke-OpsBackup -Timestamp '2026-11-26 02:00:00' -MaxAttempts 4 -Verbose |
    Format-Table Status, Attempts, Removed -AutoSize
$lock | Wait-Job | Remove-Job
VERBOSE: Performing the operation "Create backup of C:\Users\labadmin\pslab\data (5 items)" on target "C:\Users\labadmin\pslab\backups\pslab-data-20261126-020000.zip".
VERBOSE: attempt 1/4 failed (IOException); retrying in 341 ms
VERBOSE: attempt 2/4 failed (IOException); retrying in 809 ms

Status  Attempts Removed
------  -------- -------
Created        3       1

那次运行的日志

{"ts":"2026-11-25T02:03:12.361Z","level":"info","event":"backup.started","runId":"3214c421","archive":"C:\\Users\\labadmin\\pslab\\backups\\pslab-data-20261126-020000.zip","items":5,"source":"C:\\Users\\labadmin\\pslab\\data"}
{"ts":"2026-11-25T02:03:12.817Z","level":"warning","event":"backup.retry","runId":"3214c421","attempt":1,"delayMs":325,"error":"The process cannot access the file 'C:\\Users\\labadmin\\pslab\\data\\access.log' because it is being used by another process."}
{"ts":"2026-11-25T02:03:13.195Z","level":"warning","event":"backup.retry","runId":"3214c421","attempt":2,"delayMs":982,"error":"The process cannot access the file 'C:\\Users\\labadmin\\pslab\\data\\access.log' because it is being used by another process."}
{"ts":"2026-11-25T02:03:14.244Z","level":"info","event":"backup.created","runId":"3214c421","archive":"C:\\Users\\labadmin\\pslab\\backups\\pslab-data-20261126-020000.zip","attempts":3,"sizeKB":8.0}

时间戳是 UTC(02:03 UTC = 实验机所在时区 11 月 24 日晚上),与归档名使用的 -Timestamp 无关。

整个运行期间都被锁:重试耗尽

$fs = [System.IO.File]::Open("$PWD/data/access.log", 'Open', 'Read', 'None')    # never released during the run
try {
    Invoke-OpsBackup -Timestamp '2026-11-27 02:00:00' -BaseDelayMs 200
}
catch {
    "caught: $($_.FullyQualifiedErrorId)"
    "type:   $($_.Exception.GetType().FullName)"
}
finally { $fs.Dispose() }
Test-Path ./backups/pslab-data-20261127-020000.zip
Get-Content ./backups/opskit-backup.jsonl | ConvertFrom-Json | Where-Object level -ne 'info' |
    Select-Object -Last 3 | Format-Table level, event, attempt, delayMs, reason -AutoSize
caught: CompressArchiveUnauthorizedAccessError,Invoke-OpsBackup
type:   System.IO.IOException
False

level   event         attempt delayMs reason
-----   -----         ------- ------- ------
warning backup.retry        1     168
warning backup.retry        2     279
error   backup.failed                 CompressArchiveUnauthorizedAccessError,Invoke-OpsRetry

原始异常类型经过两次重新抛出仍然保留(Invoke-OpsRetry 和 Invoke-OpsBackup 都用 ThrowTerminatingError($_)),所以调用者仍可 catch [System.IO.IOException]。没有留下不完整的归档。

对调用者是语句终止

Invoke-OpsBackup -Source ./nope; 'same line: not reached?'
'next statement'
try { Invoke-OpsBackup -Source ./nope } catch { "caught: $($_.FullyQualifiedErrorId)" }
Invoke-OpsBackup: Backup source not found: ./nope
same line: not reached?
next statement
caught: OpsKit.BackupSourceNotFound,Invoke-OpsBackup

夜间包装脚本(scripts/Invoke-NightlyBackup.ps1)

<#
.SYNOPSIS
    Nightly entry point: backs up ~/pslab/data with OpsKit and verifies the archive.
.DESCRIPTION
    Exit codes: 0 success (or nothing to do); 1 backup failed; 2 configuration missing;
                3 source folder missing; 4 archive failed verification.
.EXAMPLE
    pwsh -NoProfile -NonInteractive -File ./scripts/Invoke-NightlyBackup.ps1 -WhatIf
#>
#Requires -Version 7.4
[CmdletBinding(SupportsShouldProcess)]
param(
    [datetime]$Timestamp = (Get-Date),
    [string]$Source,
    [ValidateRange(1, 10)][int]$MaxAttempts = 3,
    [ValidateRange(0, 60000)][int]$BaseDelayMs = 500
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'                    # every error at this boundary is terminating
$PSNativeCommandUseErrorActionPreference = $true   # and so is a native non-zero exit code

try {
    Import-Module (Join-Path $PSScriptRoot '..' 'OpsKit' 'OpsKit.psd1') -Force
    $backup = @{ Timestamp = $Timestamp; MaxAttempts = $MaxAttempts; BaseDelayMs = $BaseDelayMs }
    if ($Source) { $backup.Source = $Source }
    # Pass -WhatIf explicitly: a preference variable in this script's scope does not reliably
    # reach functions in another module (it only does when this script runs in the global scope).
    $backup.WhatIf = [bool]$WhatIfPreference
    $result = Invoke-OpsBackup @backup

    if ($result.Status -in 'Created', 'Exists') {
        # Trust, but verify: open the archive and count its entries.
        Add-Type -AssemblyName System.IO.Compression.FileSystem
        $zip = $null
        try {
            $zip = [System.IO.Compression.ZipFile]::OpenRead($result.Archive)
            $entries = $zip.Entries.Count
        }
        catch {
            $err = [System.Management.Automation.ErrorRecord]::new($_.Exception.GetBaseException(),
                'OpsKit.ArchiveInvalid', 'InvalidData', $result.Archive)
            throw $err
        }
        finally { if ($zip) { $zip.Dispose() } }
        Write-Information "verified $entries entries in $(Split-Path $result.Archive -Leaf)" -InformationAction Continue
    }
    $result
    exit 0
}
catch {
    $code = switch -Wildcard ($_.FullyQualifiedErrorId) {
        'OpsKit.ConfigNotFound*'       { 2 }
        'OpsKit.BackupSourceNotFound*' { 3 }
        'OpsKit.ArchiveInvalid*'       { 4 }
        default                        { 1 }
    }
    # One greppable line on stderr for the scheduler / CI log, then a meaningful exit code.
    [Console]::Error.WriteLine("Invoke-NightlyBackup: exit $code [$($_.FullyQualifiedErrorId)] $($_.Exception.Message)")
    exit $code
}
# a naive wrapper for comparison: scripts/Naive-Nightly.ps1
Import-Module (Join-Path $PSScriptRoot '..' 'OpsKit' 'OpsKit.psd1') -Force
Invoke-OpsBackup -Source ./nope
'Backup finished'
pwsh -NoProfile -NonInteractive -File ./scripts/Naive-Nightly.ps1; "exit=$LASTEXITCODE"
pwsh -NoProfile -NonInteractive -File ./scripts/Invoke-NightlyBackup.ps1 -Source ./nope; "exit=$LASTEXITCODE"
pwsh -NoProfile -NonInteractive -File ./scripts/Invoke-NightlyBackup.ps1 -Timestamp '2026-11-28 02:00' -WhatIf | Out-Null; "exit=$LASTEXITCODE"
Invoke-OpsBackup: C:\Users\labadmin\pslab\scripts\Naive-Nightly.ps1:2
Line |
   2 |  Invoke-OpsBackup -Source ./nope
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Backup source not found: ./nope
Backup finished
exit=0
Invoke-NightlyBackup: exit 3 [OpsKit.BackupSourceNotFound,Invoke-OpsBackup] Backup source not found: ./nope
exit=3
What if: Performing the operation "Create backup of C:\Users\labadmin\pslab\data (5 items)" on target "C:\Users\labadmin\pslab\backups\pslab-data-20261128-020000.zip".
exit=0

简陋的包装脚本打印了错误和 “Backup finished”,调度器看到的是 exit 0。加固后的包装脚本返回 3。-WhatIf 运行以 0 退出且没有创建任何东西(它的 “What if” 行和子进程的其他输出一起进了 Out-Null)。

本课在自己的包装脚本中发现的一个缺陷 Invoke-NightlyBackup.ps1 的第一版没有把 -WhatIf 传给 Invoke-OpsBackup,而是依赖 $WhatIfPreference。在 pwsh -File 下这样可行,因为 -File 脚本运行在全局作用域中,模块函数能看到它。用 & ./scripts/Invoke-NightlyBackup.ps1 -WhatIf 调用时,脚本运行在子作用域中,模块函数就看不到这个首选项了:
verified 16 entries in pslab-data-20261129-030000.zip
old wrapper called with & -WhatIf, archive created: True
一次“演练”创建了归档——而轮转删除了最旧的一份真实备份。修复就是那行显式的 $backup.WhatIf = [bool]$WhatIfPreference;修复后,同样的调用只打印 “What if” 行,不创建任何东西。规则:跨模块边界时显式传递 -WhatIf/-Confirm。

目标:安装 OpsKit v0.3 的文件,执行备份、轮转,扛住文件被锁,并读懂日志。环境:~/pslab,PowerShell 7.4+。成本:~/pslab/backups 中约 100 KB 的归档。

创建文件:按“命令”分页(以及模块 7 中的 Invoke-OpsRetry.ps1、Write-OpsLog.ps1)创建并导入:Import-Module ./OpsKit/OpsKit.psd1 -Force; (Get-Module OpsKit).Version → 0.3.0。
预览、运行、重跑,使用 -Timestamp '2026-11-24 10:00:00':预期状态依次为 WhatIf、Created、Exists(见“命令”分页)。
轮转:用 -Keep 30 创建八份较早的归档,用 -WhatIf 预览,再真实运行并计数:剩下 7 份。解释预览(2)与真实运行(3)的差别。
文件被锁:运行锁定 1.2 秒的示例;再运行永久锁定的示例;确认没有不完整归档,并且有三条日志事件。
像运维人员一样读日志:
Get-Content ./backups/opskit-backup.jsonl | ConvertFrom-Json | Group-Object event -NoElement | Sort-Object Name | Format-Table Count, Name -AutoSize
Count Name
----- ----
   11 backup.created
    3 backup.failed
    4 backup.removed
    4 backup.retry
   12 backup.started
包装脚本的退出码:分别用 -Source ./nope 运行简陋的和加固的包装脚本,比较 $LASTEXITCODE(0 对 3)。
清理:用 Remove-OpsBackup -Keep 1 -WhatIf 看看严格轮转会删掉什么;课程结束后执行 Remove-Item ./backups -Recurse -Force。

案例 1:从来就不完整的夜间备份

问题:一次恢复测试发现,三个月来每一份归档都缺少应用正在写入的日志文件。根因:凌晨 2 点该文件被日志代理锁定;Compress-Archive 写了一个非终止错误、生成了不完整 zip,而作业退出码为 0——正是“命令”分页里复现的情形。修复:-ErrorAction Stop、对 IOException 带退避重试、删除不完整归档、验证条目数、非零退出时告警。对于始终被锁的文件,使用快照(VSS、LVM)或应用自身的导出功能,而不是重试。

案例 2:轮转删掉了仅有的好备份

问题:连续一周的失败运行每次都留下一个很小的损坏归档,轮转保留了这七个坏的,删掉了最后一份好的。根因:轮转数的是文件,而不是好备份;失败的运行又会留下文件。修复:失败的运行什么也不留下(OpsKit 会删除不完整归档);只在备份成功且验证通过后才轮转(一个不错的扩展:状态不是 Created 时跳过 Remove-OpsBackup);当最新的好归档超过 26 小时时告警。

案例 3:并不是演练的演练

问题:在变更评审中,Invoke-Backup -WhatIf(OpsKit 命令的前身)在一块快满的磁盘上创建了一个 2 GB 的归档。根因:该函数依赖 -WhatIf 传到 Compress-Archive。修复:在写操作外加上自己的 ShouldProcess——再加一个测试:带 -WhatIf 运行每个会修改状态的命令,并断言文件系统没有变化(综合实验场景 3)。

常见错误与解决

Invoke-OpsBackup: Backup source not found
$env:OPSKIT_HOME; Test-Path ~/pslab/data; (Get-OpsConfig).Backup

原因:-Source 写错、数据未生成,或 $env:OPSKIT_HOME 仍指向某个测试沙箱。解决:重新生成数据或清除该变量。

WARNING: Backup already exists, nothing to do

原因:时间戳(精确到秒)与已有归档相同。解决:这是有意的幂等行为;生产中不要传 -Timestamp。

The process cannot access the file … being used by another process(重试全部用完之后)

解决:找出持有者(Get-Process / 资源监视器 / Linux 上的 lsof);如果锁定时间很短,就调大 -MaxAttempts/-BaseDelayMs;如果文件始终被打开,就用 Backup.Exclude 排除它。

OpsKit config not found

解决:用 Get-OpsConfig -Path … 测试路径;检查 $env:OPSKIT_HOME;用 New-LabData.ps1 重新生成。

关于“错误没有被捕获”和“脚本报告成功但实际失败”,请使用“动画”分页中的交互式决策树。

命令行练习
1. 列出最近一天失败的运行及其原因。
Get-Content ~/pslab/backups/opskit-backup.jsonl | ConvertFrom-Json |
    Where-Object { $_.event -eq 'backup.failed' -and $_.ts -gt (Get-Date).AddDays(-1) } |
    Select-Object ts, runId, reason
2. 先预览,再只保留最新的三份归档。
Remove-OpsBackup -Keep 3 -WhatIf
Remove-OpsBackup -Keep 3
场景分析
运维团队因为告警太吵,要求你让夜间任务“永不失败”:每周总有一晚因文件被锁而失败。你会改什么?又拒绝改什么?

可以改:按观察到的锁定时长调整重试(更多次数或更长的基础延迟);排除始终被打开的文件,或通过快照备份它们;只在 26 小时内没有一次成功备份时告警,而不是每次尝试失败都告警。拒绝:吞掉错误或在失败时返回 exit 0——静默失败正是团队在恢复时才发现备份缺失的原因。保持退出码诚实、日志完整;让告警变得更聪明。

经核实的教学视频

没有经核实的视频讲解这一 OpsKit 设计;以下经核实的视频涵盖了它所组合的基础知识。

▶
PowerShell WhatIf and Confirm: Dry-Run Before You Delete — AISLabs AI
英文 · 预览破坏性命令
▶
Intro To Error Handling in PowerShell — ed wilson
英文 · try/catch/finally 与终止错误

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:一个只有 16 个文件中 15 个的 zip,旁边的绿色对勾在缺失的 access.log 被高亮时变红。
讲解:报告成功却不完整的备份,比失败更糟。
镜头 2 · 20–45 秒
画面:Invoke-OpsBackup 流程图依次亮起:守卫、已存在?、ShouldProcess、重试循环中一个不完整的 zip 被删除。
讲解:守卫、预览、重试、清理。
镜头 3 · 45–70 秒
画面:一排九份归档;-WhatIf 让其中两份变灰,真实运行删除了三份。
讲解:轮转继承 WhatIf——但预览只和你的代码一样诚实。
镜头 4 · 70–90 秒
画面:调度器面板显示退出码 0、1、3,旁边是对应的 JSON 事件。
讲解:退出码给机器看,JSON 行给调查问题的人看。
或测验得分 ≥ 70%

命令速查表

第 5 课全部要点:错误类型、try/catch、原生退出码、输出流、严格模式、ShouldProcess、重试与日志、OpsKit v0.3
PowerShell 7.6可复制

1. 错误模型

$Error[0]; $Error.Count; $Error.Clear(); $?
$e = $Error[0]
$e.Exception.GetType().FullName; $e.FullyQualifiedErrorId
$e.CategoryInfo; $e.TargetObject; $e.ScriptStackTrace
Get-Error -Newest 1
# non-terminating → continue · statement-terminating → next statement
# script-terminating (throw, Stop) → up to nearest try/catch

2. try / catch / finally

try { Get-Item $p -ErrorAction Stop }
catch [System.Management.Automation.ItemNotFoundException] { … }
catch [System.IO.IOException], [System.TimeoutException] { … }
catch { throw }                     # rethrow unchanged
finally { $fs.Dispose() }
$ErrorActionPreference = 'Stop'     # script boundary
cmd -ErrorAction Ignore             # local opt-out, not in $Error
cmd -ErrorVariable ev; cmd -ErrorVariable +ev

3. 报告错误(高级函数)

Write-Error 'one item failed'                 # non-terminating
$PSCmdlet.WriteError($record)
$PSCmdlet.ThrowTerminatingError($record)      # statement-terminating
throw 'fatal'                                 # script-terminating
[System.Management.Automation.ErrorRecord]::new(
  [System.IO.FileNotFoundException]::new('msg'),
  'OpsKit.ConfigNotFound', 'ObjectNotFound', $target)

4. 原生命令

git fetch; if ($LASTEXITCODE -ne 0) { throw "git: $LASTEXITCODE" }
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true   # 7.4+, default $false
catch [System.Management.Automation.NativeCommandExitException] { $_.Exception.ExitCode }
& { $PSNativeCommandUseErrorActionPreference = $false; robocopy … }
if ($LASTEXITCODE -ge 8) { throw }
tool 2>$null · tool 2>&1 | % { "$_" }        # stderr ≠ failure

5. 输出流

# 1 out · 2 error · 3 warning · 4 verbose · 5 debug · 6 information/Write-Host
f 2>&1 · f 3> warn.txt · f *> all.txt · f 6>$null
f -Verbose -InformationAction Continue
f -ErrorVariable e -WarningVariable w -InformationVariable i
$r = f 6>&1                     # capture Write-Host
Get-Variable *Preference

6. 严格模式与防御

Set-StrictMode -Version Latest
[ValidateRange(1, 365)][int]$Keep
[ValidateSet('dev','staging','prod')][string]$Env
[ValidateScript({ Test-Path -LiteralPath $_ }, ErrorMessage = 'Not found: {0}')]
if ($null -eq $x) { }            # $null on the LEFT
@($items).Count; $h.ContainsKey('k'); $h['k']
$PSCmdlet.GetUnresolvedProviderPathFromPSPath($p)   # before .NET calls

7. 安全变更

[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
if ($PSCmdlet.ShouldProcess($target, 'Action')) { change }
f -WhatIf · f -Confirm · f -Confirm:$false
OtherModule\Cmd -WhatIf:$WhatIfPreference     # cross-module: pass it!
Add-Content $log $line -WhatIf:$false          # logs during -WhatIf
if (Test-Path $target) { return }              # idempotent

8. 重试、超时、日志、OpsKit

Invoke-OpsRetry -RetryOn ([System.IO.IOException]) -MaxAttempts 4 { … -ErrorAction Stop }
$j | Wait-Job -Timeout 5; $j | Stop-Job
Invoke-RestMethod $u -TimeoutSec 10
[ordered]@{ ts = …; level = 'info'; event = 'x' } | ConvertTo-Json -Compress -Depth 4
Invoke-OpsBackup -WhatIf; Invoke-OpsBackup -Verbose
Remove-OpsBackup -Keep 7 -WhatIf
pwsh -NoProfile -NonInteractive -File ./scripts/Invoke-NightlyBackup.ps1; $LASTEXITCODE

综合实验 + 结业测验

编写 ~/pslab/scripts/Test-OpsFailure.ps1:一个故障注入脚本,驱动夜间备份的每一条错误路径——成功、幂等重跑、-WhatIf、短暂与持续的文件锁、缺少源目录、归档损坏、缺少配置——并在沙箱中检查退出码、归档文件和日志事件
约 25 分钟仅本机综合 M1–M8

场景

在 OpsKit v0.3 上线到团队服务器之前,你必须证明夜间任务说的是真话:每种失败都产生一个非零且互不相同的退出码和一条日志事件;没有任何东西做到一半;-WhatIf 不改变任何东西。你不会拿真实备份来做这个测试。脚本在 ~/pslab/tmp/fi 中搭建沙箱,把 $env:OPSKIT_HOME 指向它,像调度器那样以独立进程运行 Invoke-NightlyBackup.ps1(模块 8)八次,每次注入一种故障,并检查结果。

故障注入脚本(M1–M8)——保存为 ~/pslab/scripts/Test-OpsFailure.ps1:
<#
.SYNOPSIS
    Failure injection for Invoke-NightlyBackup.ps1: drives every error path and checks
    exit codes, archives and the JSON-lines log.
.DESCRIPTION
    Works in a throw-away OpsKit root (~/pslab/tmp/fi) via $env:OPSKIT_HOME, so real
    backups are never touched. Exit code: 0 all scenarios passed, 1 otherwise.
#>
#Requires -Version 7.4
[CmdletBinding()]
param([string]$Root = (Join-Path $PSScriptRoot '..' 'tmp' 'fi'))
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

$Root    = [System.IO.Path]::GetFullPath($Root)
$nightly = Join-Path $PSScriptRoot 'Invoke-NightlyBackup.ps1'
$data    = Join-Path $Root 'data'
$backups = Join-Path $Root 'backups'
$logFile = Join-Path $backups 'opskit-backup.jsonl'

# Fresh sandbox: a copy of the dataset, no backups yet.
if (Test-Path -LiteralPath $Root) { Remove-Item -LiteralPath $Root -Recurse -Force }
$null = New-Item -ItemType Directory -Path $Root
Copy-Item -LiteralPath (Join-Path $PSScriptRoot '..' 'data') -Destination $data -Recurse
$env:OPSKIT_HOME = $Root                     # inherited by every child pwsh

function Invoke-Scenario {
    param([string]$Name, [int]$ExpectExit, [string[]]$Arguments = @(), [string]$ExpectEvent, [scriptblock]$Check = { $true })
    $before = if (Test-Path -LiteralPath $logFile) { @(Get-Content -LiteralPath $logFile).Count } else { 0 }
    $stderr = Join-Path $Root 'stderr.txt'
    $null = pwsh -NoProfile -NonInteractive -File $nightly @Arguments 2> $stderr
    $exit = $LASTEXITCODE
    $events = @(if (Test-Path -LiteralPath $logFile) {
        Get-Content -LiteralPath $logFile | Select-Object -Skip $before | ConvertFrom-Json | ForEach-Object event
    })
    $eventOk = -not $ExpectEvent -or $events -contains $ExpectEvent
    [pscustomobject]@{
        Scenario = $Name
        Expected = $ExpectExit
        Exit     = $exit
        Events   = ($events | Group-Object -NoElement | ForEach-Object { '{0}x{1}' -f $_.Count, ($_.Name -replace '^backup\.') }) -join ' '
        Passed   = ($exit -eq $ExpectExit) -and $eventOk -and [bool](& $Check)
        Stderr   = (Get-Content -LiteralPath $stderr -Raw -ErrorAction Ignore) -replace '\s+$'
    }
}

function Lock-File([string]$Path, [int]$Milliseconds) {
    Start-ThreadJob -ArgumentList $Path, $Milliseconds {
        param($p, $ms)
        $fs = [System.IO.File]::Open($p, 'Open', 'Read', 'None')
        try { Start-Sleep -Milliseconds $ms } finally { $fs.Dispose() }   # Stop-Job must release the lock too
    }
    Start-Sleep -Milliseconds 300            # make sure the lock is taken before the child starts
}
$zipFor = { param($ts) Join-Path $backups ('pslab-data-{0:yyyyMMdd-HHmmss}.zip' -f [datetime]$ts) }

$results = [System.Collections.Generic.List[object]]::new()

# 1. Happy path
$results.Add((Invoke-Scenario 'happy path' 0 @('-Timestamp', '2026-11-24 01:00') 'backup.created' { Test-Path (& $zipFor '2026-11-24 01:00') }))
# 2. Same timestamp again: idempotent, nothing written
$results.Add((Invoke-Scenario 'rerun is idempotent' 0 @('-Timestamp', '2026-11-24 01:00') -Check { @(Get-ChildItem $backups -Filter *.zip).Count -eq 1 }))
# 3. -WhatIf: no archive may appear
$results.Add((Invoke-Scenario '-WhatIf changes nothing' 0 @('-Timestamp', '2026-11-24 02:00', '-WhatIf') -Check { -not (Test-Path (& $zipFor '2026-11-24 02:00')) }))
# 4. Transient lock (2.5 s): retried, then success
$job = Lock-File (Join-Path $data 'access.log') 2500
$results.Add((Invoke-Scenario 'transient lock is retried' 0 @('-Timestamp', '2026-11-24 03:00', '-MaxAttempts', '6') 'backup.retry'))
$job | Wait-Job | Remove-Job
# 5. Persistent lock (15 s): retries exhausted -> exit 1, no partial archive left
$job = Lock-File (Join-Path $data 'access.log') 15000
$results.Add((Invoke-Scenario 'persistent lock fails' 1 @('-Timestamp', '2026-11-24 04:00', '-BaseDelayMs', '200') 'backup.failed' { -not (Test-Path (& $zipFor '2026-11-24 04:00')) }))
$job | Stop-Job -PassThru | Remove-Job
# 6. Missing source folder -> exit 3
$results.Add((Invoke-Scenario 'missing source' 3 @('-Source', (Join-Path $Root 'nope')) 'backup.failed'))
# 7. Corrupt archive with the requested name -> verification fails -> exit 4
Set-Content -LiteralPath (& $zipFor '2026-11-24 05:00') -Value 'not a zip'
$results.Add((Invoke-Scenario 'corrupt archive detected' 4 @('-Timestamp', '2026-11-24 05:00')))
# 8. Missing configuration -> exit 2
Rename-Item -LiteralPath (Join-Path $data 'opskit.config.psd1') -NewName 'opskit.config.psd1.bak'
$results.Add((Invoke-Scenario 'missing config' 2 @('-Timestamp', '2026-11-24 06:00')))
Rename-Item -LiteralPath (Join-Path $data 'opskit.config.psd1.bak') -NewName 'opskit.config.psd1'

$results | Format-Table Scenario, Expected, Exit, Passed, Events -AutoSize | Out-Host
$results | Where-Object Stderr | ForEach-Object { "stderr [$($_.Scenario)]: $($_.Stderr)" } | Out-Host
$failed = @($results | Where-Object { -not $_.Passed })
if ($failed) { Write-Warning "$($failed.Count) scenario(s) failed: $($failed.Scenario -join ', ')"; exit 1 }
'All failure scenarios behaved as designed.'
exit 0
#注入的故障覆盖的错误路径预期退出码 / 事件
1无正常路径0 / backup.created
2相同时间戳幂等(M6)0 / 无事件,仍只有一个归档
3-WhatIf跨进程、跨模块边界的 ShouldProcess(M6)0 / 无归档
4锁定 2.5 秒终止的 IOException → 重试(M2、M7)0 / backup.retry
5锁定 15 秒重试耗尽、清理、按类型重新抛出(M7、M8)1 / backup.failed,无不完整 zip
6缺少源目录守卫语句、ThrowTerminatingError、id → 退出码(M2、M5)3 / backup.failed
7与归档同名的垃圾文件对“已存在”的验证(M8)4
8配置被改名嵌套命令中的错误到达边界(M1)2

从测试脚本的角度看,子进程是一个原生命令(M3):它的退出码进入 $LASTEXITCODE,stderr 被重定向到文件(M4)。测试脚本自身以严格模式和 Stop 运行(M5)。Lock-File 辅助函数在 finally 中释放文件句柄——第一版没有这样做,结果 Stop-Job 让 access.log 在后续场景中一直被锁(编写本实验时发现)。

运行它:
Set-Location ~/pslab
pwsh -NoProfile -NonInteractive -File ./scripts/Test-OpsFailure.ps1; "exit=$LASTEXITCODE"
Scenario                  Expected Exit Passed Events
--------                  -------- ---- ------ ------
happy path                       0    0   True 1xcreated 1xstarted
rerun is idempotent              0    0   True
-WhatIf changes nothing          0    0   True
transient lock is retried        0    0   True 1xcreated 3xretry 1xstarted
persistent lock fails            1    1   True 1xfailed 2xretry 1xstarted
missing source                   3    3   True 1xfailed
corrupt archive detected         4    4   True
missing config                   2    2   True

stderr [persistent lock fails]: Invoke-NightlyBackup: exit 1 [CompressArchiveUnauthorizedAccessError,Invoke-OpsBackup] The process cannot access the file 'C:\Users\labadmin\pslab\tmp\fi\data\access.log' because it is being used by another process.
stderr [missing source]: Invoke-NightlyBackup: exit 3 [OpsKit.BackupSourceNotFound,Invoke-OpsBackup] Backup source not found: C:\Users\labadmin\pslab\tmp\fi\nope
stderr [corrupt archive detected]: Invoke-NightlyBackup: exit 4 [OpsKit.ArchiveInvalid] The parameter is incorrect. : 'C:\Users\labadmin\pslab\tmp\fi\backups\pslab-data-20261124-050000.zip'.
stderr [missing config]: Invoke-NightlyBackup: exit 2 [OpsKit.ConfigNotFound,Get-OpsConfig] OpsKit config not found: C:\Users\labadmin\pslab\tmp\fi\data\opskit.config.psd1
All failure scenarios behaved as designed.
exit=0

整个运行约 12 秒。“The parameter is incorrect” 是 Windows 上 ZipFile.OpenRead 打开一个 11 字节文本文件时产生的基础异常;包装脚本映射为 exit 4 的依据是 id OpsKit.ArchiveInvalid。

证明测试脚本能捕获回归:在 Invoke-OpsBackup.ps1 中把 if (Test-Path -LiteralPath $zip) { 改成 if ($false) { 以破坏幂等,重新运行,然后恢复这一行:
Scenario                  Expected Exit Passed Events
--------                  -------- ---- ------ ------
happy path                       0    0   True 1xcreated 1xstarted
rerun is idempotent              0    0   True 1xcreated 1xretry 1xstarted
-WhatIf changes nothing          0    0   True
transient lock is retried        0    0   True 1xcreated 2xretry 1xstarted
persistent lock fails            1    1   True 1xfailed 2xretry 1xstarted
missing source                   3    3   True 1xfailed
corrupt archive detected         4    0  False 1xcreated 1xretry 1xstarted
missing config                   2    2   True
…
WARNING: 1 scenario(s) failed: corrupt archive detected
exit=1

看看事件:没有存在性检查时,Compress-Archive 因目标已存在而失败,重试钩子把已有的归档当作不完整归档删除,下一次尝试又重新生成了它。在场景 2 中,这悄悄覆盖了一份好的备份(检查仍然通过——只有一个归档);在场景 7 中,测试脚本抓住了它:exit 0 而不是 4。两点教训:守卫要排在清理逻辑之前;除了退出码,还要对事件做断言。

扩展它(轮到你了):增加一个场景,在 pwsh -Command 中用 & … -WhatIf 运行包装脚本(模块 8 提示框中的情形),并断言没有归档;再增加一个包装脚本中原生命令失败的场景(例如在备份后加上 git -C $data status,并在仓库外运行——在 $PSNativeCommandUseErrorActionPreference = $true 时包装脚本返回哪个退出码?)。
验收清单
清理:Remove-Item ~/pslab/tmp/fi -Recurse -Force

开放式自测

1. 把一个来自 Compress-Archive 的 IOException 一路追踪到调度器看到的退出码。

Compress-Archive(带 -ErrorAction Stop)在 Invoke-OpsRetry 的 try 中抛出脚本终止的 IOException;catch 用 -RetryOn 检查异常链,通过 -OnRetry 记录日志,等待后重试;最后一次尝试之后调用 ThrowTerminatingError($_);Invoke-OpsBackup 的 catch 记录 backup.failed,删除不完整归档,再次调用 ThrowTerminatingError($_);在包装脚本中,这个语句终止错误被边界处的 try/catch 捕获,id 映射为 1,一行写到 stderr,exit 1 让 pwsh -File 进程以 1 结束。

2. 为什么 Invoke-OpsBackup “抛出了错误”,简陋的包装脚本却以 0 退出?

它使用 ThrowTerminatingError,这是语句终止的:没有 try/catch 或 Stop 时,调用者的下一条语句照常执行,脚本正常结束(exit 0)。只有脚本终止错误(或显式的 exit N)才会改变 -File 的退出码。

3. 什么时候吞掉错误是对的?

当错误是预期内且无害的、这个决定是显式且局部的、并且留下了记录:Get-Command az -ErrorAction Ignore 用于测试工具是否存在;Write-OpsLog 把日志失败变成警告,使日志不会拖垮备份。永远不要全局吞掉,永远不要对变更操作静默吞掉。

4. 举出本课中出现过的、让 -WhatIf 预览与真实运行不一致的两个原因。

看不到首选项的代码路径(其他脚本模块——Compress-Archive、通过 & 调用的第一版包装脚本);以及依赖变更本身的逻辑(轮转把本会创建的归档计算在内:删除 2 份对 3 份)。

来源与版本说明

2026-11-24 在 PowerShell 7.6.10(.NET 10.0.15,Windows 11)上逐条运行命令核实行为;文档链接均确认返回 HTTP 200;视频通过 YouTube oEmbed 核实
核实日期 2026-11-24
主题核实结果来源(访问于 2026-11-24)
错误类型与 $Error用 Show-ErrorKinds.ps1 复现了非终止、语句终止和脚本终止的行为(throw 导致 exit 1);SilentlyContinue 会记入 $Error,Ignore 不会;捕获了 Get-Error 输出Everything about exceptions;Get-Error;about_Automatic_Variables
try/catch、throw、ThrowTerminatingError、trap使用 -ErrorAction Stop 后类型化 catch 匹配原始异常;ThrowTerminatingError 对调用者是语句终止,throw 是脚本终止;$ErrorActionPreference = 'SilentlyContinue' 隐藏了转换错误;绑定错误不受 -ErrorAction 影响;try 块也能捕获语句终止错误(注释掉 Stop 后包装脚本仍然有效)about_Try_Catch_Finally;about_Throw;about_Trap;about_CommonParameters
原生命令$PSNativeCommandUseErrorActionPreference 默认为 False;配合 Stop 会抛出 NativeCommandExitException(ProgramExitedWithNonZeroCode、.ExitCode);stderr 不会设置 $? 也不会触发 Stop;被重定向的 stderr 行是不进入 $Error 的 ErrorRecord;robocopy exit 1 引发了异常;git 2.51.2 退出码为 129 / 128about_Preference_Variables;What's New in PowerShell 7.4;about_Redirection
输出流各流的记录类型;首选项为 SilentlyContinue 时 -InformationVariable 仍能收集记录;Write-Host 带 PSHOST 标签;*> 写出了 Write-Information 行,但没有 verbose/debug 行;嵌套的 -Verbose 会传入高级函数about_Output_Streams;about_Redirection
严格模式与防御式编程Latest 能捕获未初始化变量、不存在的属性(包括用点号访问的哈希表键)、方法调用语法和越界索引;这些错误是语句终止的;子作用域可以关闭严格模式;$arr -eq $null 是过滤Set-StrictMode;Everything about $null;about_Functions_Advanced_Parameters
ShouldProcess-WhatIf 输出格式;编译型 cmdlet 和同模块函数会继承 $WhatIfPreference;另一个脚本模块中的函数(测试模块、Compress-Archive 1.2.7)不会,除非首选项设置在全局作用域;WhatIf 下 Add-Content 被跳过;-NonInteractive 下 ShouldProcess 询问会抛出异常Everything about ShouldProcess;about_Functions_CmdletBindingAttribute;How to request confirmations
重试、超时、会话记录种子 42 的重试时序;Wait-Job -Timeout 后作业仍为 Running;取消令牌抛出 TaskCanceledException;-TimeoutSec 2 在 2.0 秒时取消了一个缓慢的本地请求,-OperationTimeoutSeconds 2 没有(5.2 秒后返回);会话记录遗漏了原生控制台输出;ConvertTo-Json 深度警告Invoke-RestMethod;Wait-Job;Start-Transcript
Compress-ArchiveMicrosoft.PowerShell.Archive 1.2.7(脚本模块):文件被锁且不带 Stop → 非终止的 Write-Error,$? = True,15 个条目的不完整归档;带 Stop → IOException,id 为 CompressArchiveUnauthorizedAccessError,ZipArchiveHelper,不留归档;-LiteralPath 正确归档了全部 12 个奇怪文件名Compress-Archive
OpsKit v0.3模块 8 的全部运行和 8 场景故障注入测试(12 秒)均在 7.6.10 上完成;编写过程中发现并修复了三个缺陷:Write-OpsLog 中的相对日志路径、包装脚本跨模块边界依赖 $WhatIfPreference、测试脚本的文件锁未被 Stop-Job 释放本课的实际运行

视频核实说明

只列出了 2026-11-24 通过 YouTube oEmbed(https://www.youtube.com/oembed?url=…&format=json)确认过标题和频道的视频:

oEmbed 只能核实标题和频道;视频未被逐段观看,描述来自标题和搜索摘要。许多视频使用 Windows PowerShell 5.1,其原生 stderr 处理与 7.x 不同(模块 3)。没有找到关于 $PSNativeCommandUseErrorActionPreference、7.x 六个输出流、Set-StrictMode、跨模块 -WhatIf 传递、重试/退避与 JSON 行日志的经核实视频;以本课的实际运行和官方文档为准。

语音讲解说明

“语音”分页使用浏览器内置的 Web Speech API(zh-CN)朗读讲解稿,英文术语可用 en-US 发音;不需要网络。课件无法嵌入 MP3 或生成视频;讲解稿和分镜可交给 TTS 或视频工具使用。

已知局限

  • 运行环境:所有“实际输出(7.6.10)”均来自 Windows 11 上的 PowerShell 7.6.10;路径被替换为 C:\Users\labadmin\pslab\…,OpsKit 根目录通过 $env:OPSKIT_HOME 指向实验目录。看起来像交互式输入的代码片段,是通过一个小型宿主脚本非交互地运行的(pwsh -NonInteractive),它像逐条键入那样执行每条顶层语句;因此脚本终止错误会结束片段的其余部分,这与脚本中的行为一致。
  • 未在 Linux 或 macOS 上运行:sh -c 'exit 3'、rsync 以及 Unix 上的文件锁行为(建议性锁:FileShare.None 在那里不会以同样的方式阻止其他进程)均依据文档描述。文中的文件锁重试场景是 Windows 特有的。
  • 依赖时序或随机性的值(重试延迟、场景 4/5 中的重试次数、RunId、时间戳)每次运行都不同;带种子的 Invoke-OpsRetry 示例(种子 42)可以复现。
  • “预期输出”代码块:Linux/macOS 命令和与 Windows PowerShell 5.1 的对比没有运行。打开非 zip 文件时的确切基础异常(“The parameter is incorrect”)与平台有关。
  • 轮转预览会少报一次删除(这是本教学版本的设计);动画简化了引擎内部细节(用于传播的确切异常类型、宿主询问流程)。