PowerShell 第 8 课:测试、调试、质量与发布

从“在我机器上能跑”到值得信赖的发布:用断点代替打印语句定位问题,让 PSScriptAnalyzer 批量拦截常见错误,用 Pester 6 测试和 Mock 证明行为,测量覆盖率与速度,最后通过构建脚本和 GitHub Actions 工作流发布 OpsKit v1.0
PowerShell 7.6 LTS(7.6.10)Pester 6.2.0PSScriptAnalyzer 1.25.0仅本地 · 免费已验证 · 2026-11-24
学习路径中的位置 第 1–7 课打下了语言、工具开发与自动化的基础,并逐步构建了贯穿项目 OpsKit:第 3 课的松散函数(v0.1)、第 4 课发布到本地文件夹仓库的脚本模块(v0.2)、第 5 课带 SupportsShouldProcess 和 JSON 日志的 Invoke-OpsBackup(v0.3)、第 6 课的 Invoke-OpsHealthCheck(v0.4),以及第 7 课的 Invoke-OpsApi 和 Get-OpsCloudInventory(v0.5)。但到目前为止,没有任何东西能证明这些代码是对的。本课为代码加上工程纪律 —— 调试器、静态分析、带 Mock 的单元测试、覆盖率、性能测量、签名和 CI 流水线 —— 并以里程碑 OpsKit v1.0.0 收尾:51 个测试、100% 命令覆盖率、0 条分析告警、一个 build.ps1 和一个 .nupkg。对照 Bash 课程,对应的工具是 set -x、ShellCheck 和 bats。
总体学习目标
  • 用断点而不是 Write-Host 调试:用 Set-PSBreakpoint 设置行、命令和变量断点,熟练使用控制台调试器(s v o c k l),会用 Wait-Debugger、Set-PSDebug -Trace 以及 VS Code 的 “Launch Current File” 配置。
  • 运行 PSScriptAnalyzer,读懂规则严重级别,用 PSScriptAnalyzerSettings.psd1 控制它(并且知道同名文件会被自动加载),用带理由的特性抑制单条告警,用 Invoke-Formatter 格式化代码。
  • 用 Pester 6 编写测试:Describe / Context / It、BeforeAll / BeforeEach、新的 Should-* 断言和经典 Should -Be、TestDrive: 与 -ForEach 数据驱动 —— 并能解释让朴素测试文件出错的发现阶段与运行阶段。
  • 用 -ModuleName 和 -ParameterFilter Mock 依赖(Invoke-WebRequest、Invoke-RestMethod、Get-Date、原生 git),用 Should-Invoke 断言调用,用 InModuleScope 访问私有函数,测试 -WhatIf 和错误路径。
  • 用 New-PesterConfiguration 配置 CI 运行:JaCoCo 覆盖率、NUnit/JUnit 结果文件和退出码(Run.Exit、Run.Throw)—— 并且知道覆盖率目标未达标本身不会让运行失败。
  • 先测量再优化:用 Measure-Command 比较数组 +=、List[T] 与管道捕获,字符串 +=、StringBuilder 与 -join,Where-Object 与 .Where(),以及用 -Filter 尽早筛选。
  • 理解 Authenticode 签名、AllSigned、受限语言模式、基于 ModuleVersion + Prerelease 的语义化版本、CHANGELOG,以及在 Windows、Ubuntu、macOS 上测试、打标签时发布的 GitHub Actions 工作流。
  • 用 build.ps1(Analyze、Test、Package)发布 OpsKit v1.0.0:出错即以退出码 1 失败、强制 80% 覆盖率阈值、生成 OpsKit.1.0.0.nupkg。

1 小时时间分配

#时间模块核心内容动画 / 交互实验(~/pslab)
0课前准备Pester 6.2.0 和 PSScriptAnalyzer 1.25.0 与系统自带的 Pester 3.4.0 并存;VS Code PowerShell 扩展;OpsKit v0.5 目录结构自检清单加载正确的 Pester,运行第一个测试
100–06调试Set-PSBreakpoint(行、命令、变量)、调试器命令、$PSDebugContext、Wait-Debugger、Set-PSDebug -Trace / -Strict、Write-Debug、launch.json调试器单步演示:s / v / o / c用断点和 Action 找出错误的统计结果
206–13静态分析Invoke-ScriptAnalyzer、严重级别、配置文件、自动加载、抑制、Invoke-Formatter、-Fix分析器流水线清理一个故意写坏的脚本
313–21Pester 基础Describe / Context / It、BeforeAll / BeforeEach、发现与运行、Should-* 与 Should -Be、TestDrive、-ForEach核心动画:发现阶段与运行阶段为 Get-OpsServer 和 Invoke-OpsBackup 写测试
421–28MockMock -ModuleName -ParameterFilter、Should-Invoke、InModuleScope、测试 -WhatIf 与错误、原生命令、REST 重试Mock 解析器不联网测试 Test-OpsEndpoint 和 Invoke-OpsApi
528–35覆盖率与 CI 输出New-PesterConfiguration、CodeCoverage(JaCoCo)、TestResult(NUnitXml / JUnitXml)、Run.Exit、Run.Throw、-CI从测试运行到 CI 状态为 OpsKit 生成覆盖率和结果文件
635–42性能Measure-Command;+= vs List[T] vs $x = foreach;StringBuilder;.Where();foreach vs ForEach-Object;-Filter开销赛跑在自己机器上对比六种写法
742–50安全与发布Authenticode、AllSigned、受限语言模式、SemVer + Prerelease、CHANGELOG、GitHub Actions 矩阵与发布发布流水线编写并校验 .github/workflows/opskit.yml
850–60OpsKit v1.0测试套件、分析告警清理、Update-PSModuleManifest、build.ps1、Compress-PSResource、本地文件夹仓库build.ps1 守门人 + 排错树发布 OpsKit 1.0.0
—课后速查表 · 综合实验端到端运行 build.ps1,故意破坏它,逐项核对验收标准结业测验(12 题)out/repo 中的 OpsKit.1.0.0.nupkg

知识覆盖矩阵

目标技能M1M2M3M4M5M6M7M8关键命令实验
交互式与无人值守调试✓······✓Set-PSBreakpoint、Wait-Debugger、Set-PSDebugM1
静态分析与格式化·✓····✓✓Invoke-ScriptAnalyzer、Invoke-FormatterM2、M8
编写 Pester 6 测试··✓✓✓··✓Describe、It、Should-Be、TestDriveM3、M8
用 Mock 隔离依赖···✓···✓Mock、Should-Invoke、InModuleScopeM4、M8
覆盖率、报告与退出码····✓·✓✓New-PesterConfiguration、Run.ExitM5、综合实验
测量并修复性能问题·····✓··Measure-Command、List[T]、-FilterM6
签名、版本与发布文档······✓✓Get-AuthenticodeSignature、[semver]、Update-PSModuleManifestM7、M8
自动化构建与 CI·✓··✓·✓✓build.ps1、GitHub Actions、Compress-PSResourceM8、综合实验

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

主题为什么不在本课去哪里学
编写自定义 PSScriptAnalyzer 规则、自定义 Should-* 断言(New-ShouldAssertion)面向工具作者;内置规则和断言已足够覆盖 OpsKitPSScriptAnalyzer 文档;Pester 6.1 发布说明
Pester 的实验性并行运行器(Run.Parallel)6.x 中仍是实验特性;Mock 和共享状态需要特别处理Pester 6.0 发布说明
针对真实云资源的集成测试需要账号且会产生费用;本课用 Mock 隔离第 7 课、Azure 与 AWS 课程
公共 CA 的代码签名证书、WDAC / App Control 策略属于组织级 PKI 和设备策略,无法在实验笔记本上复现about_Signing、Microsoft App Control 文档
Azure DevOps / GitLab 流水线思路与 GitHub Actions 相同;学会一种 CI 即可迁移Git 课程及对应 CI 文档
贯穿整个课程的生产故障与面试题由第 9 小时集中讲解第 9 课

如何使用本材料

每个模块 10 个分页
原理 · 图解 · 动画 · 命令 · 实验 · 生产案例 · 排错 · 测验 · 语音 · 视频。模块 3 的动画(发现与运行)能解释大多数“测试里拿到 $null”的问题 —— 写测试前先看它。
学习进度
测验得分 ≥ 70% 或点击“标记本模块为已完成”都会计入进度。进度保存在本浏览器的 localStorage 中(如果浏览器禁止本地存储,刷新后会重置)。
语音讲解
“语音”分页使用浏览器内置的 Web Speech API(zh-CN)朗读讲解稿。没有语音包时也可以直接阅读讲解稿,或交给其他 TTS 工具。
版本说明 验证日期 2026-11-24,环境为 PowerShell 7.6.10(.NET 10.0.15,Windows 11)。PowerShell Gallery 上的当前版本是 Pester 6.2.0(2026-09-09);Pester 6.0.0 于 2026-07-07 发布,带来新的 Should-* 断言、按文件进行发现与运行、基于分析器的覆盖率,并移除了 Assert-MockCalled、Pending 状态和 Mock 回落。Pester 6 支持 Windows PowerShell 5.1 和 PowerShell 7.4+。当前的 PSScriptAnalyzer 1.25.0 发布于 2026-03-20。Windows 仍在 C:\Program Files\WindowsPowerShell\Modules 中自带 Pester 3.4.0,pwsh 也能看到它 —— 模块 0 演示了误加载它的后果。模块 6 的所有耗时都来自同一台机器,你的结果会不同。

模块 0 · 准备:Pester 6、PSScriptAnalyzer 与 VS Code 调试器

让最新的 Pester 和 PSScriptAnalyzer 与系统自带的旧版 Pester 并存,确保加载的是正确版本,并为测试准备好 OpsKit v0.5 的目录结构
课前 ≈ 10 分钟本地运行 · 免费只写入 ~/pslab
前置条件
  • 第 3–5 课(高级函数、模块、SupportsShouldProcess)。第 7 课的 Invoke-OpsApi 在这里用 Mock 测试,因此不需要 API 或云账号。
  • 第 1 课在 ~/pslab/data 中生成的数据集(随时可用 ~/pslab/New-LabData.ps1 重建)。
  • 装有 PowerShell 扩展(2026.x)的 VS Code,用于模块 1 的调试器部分。其余内容在普通 pwsh 中即可完成。

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

1. 第 5 课中,[CmdletBinding(SupportsShouldProcess)] 给函数带来了什么?函数体必须调用什么?

带来 -WhatIf 和 -Confirm 参数;函数体必须把每一处修改包在 if ($PSCmdlet.ShouldProcess($target, $action)) { … } 中。模块 4 正是要测试这一点。

2. 第 4 课中,哪个文件决定模块导出什么?

清单中的 FunctionsToExport(以及根模块的 Export-ModuleMember)。私有辅助函数留在模块内部 —— 所以测试需要 -ModuleName 或 InModuleScope(模块 4)。

3. 为什么第 1 课坚持自动化要用 pwsh -File 而不是 -Command?

-File 会把脚本的 exit N 原样传给调用方;-Command 只报告 0 或 1。CI 依赖退出码(模块 5 和 8)。

第 1 步:安装 Pester 6 和 PSScriptAnalyzer

常规做法是用 PSResourceGet(7.6 自带)为当前用户安装。固定你测试时使用的版本 —— CI 也会固定同样的版本(模块 7):

Install-PSResource -Name Pester -Version 6.2.0 -Scope CurrentUser -TrustRepository
Install-PSResource -Name PSScriptAnalyzer -Version 1.25.0 -Scope CurrentUser -TrustRepository

本课的实验机不允许修改用户状态,因此改为把模块保存到一个文件夹,并把该文件夹放在 $env:PSModulePath 的最前面。这种“随项目携带模块”的做法在构建代理上也很实用:

$mods = Join-Path ~/pslab 'modules'
New-Item -ItemType Directory -Path $mods -Force | Out-Null
Save-PSResource -Name Pester, PSScriptAnalyzer -Path $mods -TrustRepository
$env:PSModulePath = $mods + [IO.Path]::PathSeparator + $env:PSModulePath   # 仅对当前会话有效

本课约定:简短的演示脚本保存为 ~/pslab/lab/<名称>.ps1,在 ~/pslab 中用 pwsh -NoProfile -File 运行,所以部分错误堆栈里会出现 C:\Users\labadmin\pslab\lab\…。OpsKit 位于 ~/pslab/OpsKit,Pester 演示文件位于 ~/pslab/demo 和 ~/pslab/gotcha。

第 2 步:“加载了错误的 Pester”陷阱

Windows 在 Windows PowerShell 的模块目录中自带 Pester 3.4.0,而 pwsh 的模块路径也包含这个目录。如果机器上没有更新的 Pester,Import-Module Pester 会悄悄加载 3.4.0,现代测试文件随之报出令人困惑的错误:

BeforeAll {
    function Get-Answer { 42 }
}
Describe 'Get-Answer' {
    It 'returns 42' {
        Get-Answer | Should-Be 42
    }
}
Get-Module Pester -ListAvailable | Select-Object Name, Version, ModuleBase | Format-Table -AutoSize
Import-Module Pester
(Get-Module Pester).Version.ToString()
Invoke-Pester ./gotcha/First.Tests.ps1
Name   Version ModuleBase
----   ------- ----------
Pester 3.4.0   C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0

3.4.0





 [-] Error occurred in test script './gotcha/First.Tests.ps1' 157ms
   RuntimeException: The BeforeAll command may only be used inside a Describe block.
   at Assert-DescribeInProgress, C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Functions\Describe.ps1: line 125
   at BeforeAll, C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Functions\SetupTeardown.ps1: line 56
   at <ScriptBlock>, C:\Users\labadmin\pslab\gotcha\First.Tests.ps1: line 1
   at <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Pester.psm1: line 297
   at Invoke-Pester, C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Pester.psm1: line 310
   at <ScriptBlock>, C:\Users\labadmin\pslab\lab\s0a.ps1: line 4
Tests completed in 157ms
Passed: 0 Failed: 1 Skipped: 0 Pending: 0 Inconclusive: 0

“The BeforeAll command may only be used inside a Describe block” 是 Pester 3/4 运行 Pester 5/6 测试文件的典型特征。把新版本放在模块路径最前面,并在导入时指定最低版本:

$env:PSModulePath -split [IO.Path]::PathSeparator | Select-Object -First 2
Get-Module Pester, PSScriptAnalyzer -ListAvailable | Select-Object Name, Version | Format-Table -AutoSize
Import-Module Pester -MinimumVersion 6.0.0
Import-Module PSScriptAnalyzer
Get-Module Pester, PSScriptAnalyzer | Select-Object Name, Version | Format-Table -AutoSize
@(Get-Command -Module Pester -Name 'Should-*').Count
Invoke-Pester ./gotcha/First.Tests.ps1
C:\Users\labadmin\pslab\modules
C:\Users\labadmin\Documents\PowerShell\Modules

Name             Version
----             -------
Pester           6.2.0
PSScriptAnalyzer 1.25.0
Pester           3.4.0


Name             Version
----             -------
Pester           6.2.0
PSScriptAnalyzer 1.25.0

41

Running tests from 1 files.
[+] C:\Users\labadmin\pslab\gotcha\First.Tests.ps1 1.2s (1 test)
Tests completed in 1.24s
Tests Passed: 1, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0

导入时始终带上 -MinimumVersion 6.0.0(或在运行脚本顶部写 #Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.0.0' })。6.2.0 中匹配 Should-* 的命令有 41 个,完整列表见模块 3。

第 3 步:本课要测试的 OpsKit v0.5 结构

路径内容
~/pslab/OpsKit/OpsKit.psd1、OpsKit.psm1清单(v0.5.0)和根模块:先点源 Private/*.ps1,再点源 Public/*.ps1,只导出 Public
Public/Get-OpsServer、Get-OpsConfig、Test-OpsEndpoint、Invoke-OpsBackup、Invoke-OpsHealthCheck、Invoke-OpsApi、Get-OpsCloudInventory
Private/Resolve-OpsPath(展开 ~)、Write-OpsLog(向 $env:OPSKIT_LOG 写 JSON 行)
tests/v0.5 时为空 —— 由模块 3、4、8 填充

本课中的代码是第 3–7 课所建内容的精简重建版(函数名和参数相同,函数体简化,Invoke-OpsHealthCheck 改为顺序执行而非并行,以便 Mock)。如果你自己的 OpsKit 有所不同,这些技术同样适用。本课用到的所有源码都在模块 8 中完整列出。

# OpsKit root module: dot-source Private, then Public; export only Public.
$private = @(Get-ChildItem -Path (Join-Path $PSScriptRoot 'Private') -Filter '*.ps1' -ErrorAction Ignore)
$public  = @(Get-ChildItem -Path (Join-Path $PSScriptRoot 'Public')  -Filter '*.ps1' -ErrorAction Ignore)
foreach ($file in @($private + $public)) {
    . $file.FullName
}
Export-ModuleMember -Function $public.BaseName

第 4 步:VS Code

在 VS Code 中打开 ~/pslab/OpsKit。状态栏必须显示 PowerShell 7.6(点击版本号可切换)。扩展会在你输入时用波浪线标出 PSScriptAnalyzer 告警,并提供调试器(模块 1)。“测试”面板可以通过 Pester Tests 扩展运行 Pester 测试;本课使用命令行,以便输出可复现。

环境自检清单

风险与清理 本课的测试只写入 Pester 的 TestDrive:(每个容器结束后自动删除的临时目录)和 ~/pslab。不会向真实仓库发布任何内容,也不会创建证书:签名和发布步骤以预期输出展示。撤销准备工作:Uninstall-PSResource Pester, PSScriptAnalyzer -Version 6.2.0, 1.25.0(如果你安装过),或删除 ~/pslab/modules。不要动系统自带的 Pester 3.4.0,Windows 组件可能会用到它。

模块 1 · 调试:断点、VS Code 调试器、Set-PSDebug 与 Wait-Debugger

00:00 – 06:00 · 别再靠 Write-Host 猜:让脚本停在状态出错的地方,查看变量、单步执行;对于没人能守在调试器前的场景,保留一份非交互式的跟踪
6 分钟Set-PSBreakpoint · Wait-Debugger★★★★☆
学习目标
  • 用 Set-PSBreakpoint 设置行、命令和变量断点,列出和删除断点,并附加只记录日志、不停止的 -Action。
  • 熟练使用控制台调试器:s(单步进入)、v(单步跳过)、o(单步跳出)、c(继续)、k(调用栈)、l(列出源码)、q(退出)、?(帮助)—— 并在 [DBG] 提示符下求值任意表达式。
  • 会用 Wait-Debugger、$PSDebugContext、Set-PSDebug -Trace 1/2 和 -Strict,以及配合 -Debug 的 Write-Debug。
  • 在 VS Code 中用 “PowerShell: Launch Current File” 配置调试(F5、F9、F10、F11)。
前置条件:第 3 课(函数、[CmdletBinding()])。重要度:★★★★☆(能随时停下来看,后面每个模块都会更快)

是什么:调试器是引擎的一部分

调试器位于引擎内部,而不是编辑器中。任何宿主 —— 控制台、VS Code、远程会话 —— 都能让运行中的脚本停在断点上,在脚本作用域内提供一个嵌套的 [DBG] 提示符,然后继续执行。VS Code 只是在同一个引擎调试器上画了一层界面。

断点类型设置方式何时停止典型用途
行Set-PSBreakpoint -Script f.ps1 -Line 6(可选 -Column)即将执行该行时“这里的变量是什么值?”
命令Set-PSBreakpoint -Command Import-Csv调用该命令时(支持通配符)“谁在调用 Remove-Item,参数是什么?”
变量Set-PSBreakpoint -Variable total -Mode Write(Read、ReadWrite)变量被写入 / 读取时(已验证:Action 看到的是写入后的值)“谁改了 $total?”
代码中Wait-Debugger执行到该语句时作业、运行空间、远程会话、无法从编辑器启动的代码

为什么:打印调试无法扩展

Write-Host "x=$x" 这样的行要加上、再删掉,而且只能显示你事先猜到的内容。断点让你在出错的那一刻提出新的问题:$s | Format-List *、Get-PSCallStack,甚至调用函数。带 -Action 的断点是一条无侵入的日志行,无需修改脚本即可添加。对于无人值守的运行,Set-PSDebug -Trace 会打印执行的每一行 —— 相当于 PowerShell 的 set -x。

怎么做:[DBG] 提示符下的调试命令

按键命令作用VS Code
sStepInto执行一条语句;进入它调用的函数和脚本F11
vStepOver执行一条语句;被调用的函数整体执行完F10
oStepOut执行完当前函数或脚本,停在调用方Shift+F11
cContinue运行到下一个断点F5
qQuit停止脚本并退出调试器Shift+F5
kGet-PSCallStack显示调用栈CALL STACK 面板
l / l 10 5List显示当前行附近的源码(* 标记当前行)编辑器
? / hHelp列出命令—
任意表达式—在脚本作用域中求值:$s.Name、$total = 0DEBUG CONSOLE、VARIABLES、WATCH

单个字母同时是变量名也没关系($s 与 s),因为变量需要 $。若要打印名为 c 的变量,输入 $c。

何时用:不同场景选不同工具

场景工具
可在本地编辑器中复现VS Code F9 断点 + F5 “Launch Current File”
只有控制台(服务器、SSH)先 Set-PSBreakpoint,再运行脚本
想加日志但不改文件Set-PSBreakpoint … -Action { Write-Host … }
代码运行在作业、运行空间或其他进程中在代码中放 Wait-Debugger,再用 Debug-Job、Debug-Runspace 或 Enter-PSHostProcess
无人值守(CI、计划任务)Set-PSDebug -Trace 1、Write-Verbose/Write-Debug、Transcript —— 绝不用交互式断点
变量名拼写错误在脚本中使用 Set-StrictMode -Version Latest(比 Set-PSDebug -Strict 更好,见“命令”页)
常见误区① “断点需要 VS Code” —— 断点是引擎功能,Set-PSBreakpoint 在任何宿主中都能用。② “Set-PSDebug -Strict 能抓住所有未定义变量” —— 它等于严格模式 1.0,会忽略字符串内的变量(在“命令”页复现)。③ “生产代码里忘掉的 Wait-Debugger 无害” —— stdin 保持打开时会永远等待;stdin 已到 EOF 时会被悄悄跳过(两种情况都在 7.6.10 上验证过)。④ “-Debug 会对每条消息要求确认” —— 那是 Windows PowerShell 5.1 的行为;7.x 中它只是设置 $DebugPreference = 'Continue' 并打印。⑤ “编辑文件后行断点会跟着代码走” —— 断点绑定的是行号,在上方编辑会让它错位。

图解:断点把你带到哪里

脚本运行中Get-ProdSummary.ps1第 4 → 5 → 6 行在脚本作用域中 第 6 行 断点表行 Get-ProdSummary.ps1:6命令 Import-Csv变量 total(Write)有 -Action { … }?执行它无 Action / break → 停止 [DBG] 嵌套提示符(同一作用域)$PSDebugContext.Breakpoints · InvocationInfo$s.Name · $total · Get-PSCallStack (k)l = 列出源码 · ? = 帮助s / v / o = 单步 · c = 继续 · q = 退出宿主决定界面:控制台文本或 VS Code 面板 非交互式替代方案 Set-PSDebug -Trace 1(行)/ -Trace 2(+ 变量赋值和调用)· Write-Debug + -Debug · Write-Verbose + -Verbose Set-PSBreakpoint -Action { Write-Host … } —— 不修改脚本也能加一行日志 Wait-Debugger + Debug-Job / Debug-Runspace / Enter-PSHostProcess,用于在别处运行的代码
图 1-1:引擎在每条语句执行前检查断点表;带 Action 的断点执行后继续,普通断点在脚本自身的作用域中打开嵌套提示符

图解:单步命令与函数调用

trace-demo.ps1 1 function Get-Double([int]$n) { $n * 2 } 2 $x = 5 3 $y = Get-Double $x ◀ 断点 4 "y=$y" s(单步进入)第 3 行 → 进入 Get-Double({ 然后 $n * 2) v(单步跳过)第 3 行 → 第 4 行(Get-Double 整体执行完) o(在 Get-Double 内单步跳出)→ 回到调用方第 4 行,$y = 10
图 1-2:与“命令”页真实会话中的三步相同(s、s、o)

调试器单步演示:每条命令之后发生了什么?

选择一个场景并逐步执行。日志显示的是为本课录制的 7.6.10 真实控制台文本。

就绪。
动画背后的真实机制 引擎在每条语句执行前检查断点表(行、命令、变量)。若断点匹配且带有 -Action,就在脚本作用域中执行该 Action;除非 Action 调用了 break,否则继续执行。否则引擎触发调试停止事件,由宿主显示嵌套提示符。单步命令设置一个一次性条件(“在下一条语句停 / 在本帧的下一条语句停 / 本帧返回时停”)然后继续运行。

命令表

命令用途说明
Set-PSBreakpoint -Script f.ps1 -Line 6行断点脚本路径必须与实际运行的路径一致(使用完整路径)
Set-PSBreakpoint -Command Remove-*命令断点支持通配符;加 -Script 可限定到某个文件
Set-PSBreakpoint -Variable total -Mode Write变量断点变量名不带 $;模式 Read、Write、ReadWrite
-Action { … }执行代码而不停止在其中调用 break 可实现条件停止:-Action { if ($total -gt 3) { break } }
Get-PSBreakpoint / Disable- / Enable- / Remove-PSBreakpoint管理断点表HitCount 显示每个断点命中的次数
Wait-Debugger在此停止提交前删除(PSScriptAnalyzer 没有对应规则 —— 在 CI 中搜索它)
$PSDebugContext只在 [DBG] 停止时存在(在 -Action 中为 $null).Breakpoints、.InvocationInfo;if ($PSDebugContext) = “我在调试器里吗?”
Set-PSDebug -Trace 1 / 2 / -Off行跟踪 / 加上赋值和调用输出到调试流,形如 DEBUG: 行
Set-StrictMode -Version Latest对未定义变量、不存在的属性、错误调用报错作用于当前作用域;放在脚本和模块顶部
Write-Debug + -Debug开发者消息7.x:-Debug 设置 $DebugPreference = 'Continue'(不再提示确认)

1. 带 Action 的断点:不改脚本也能记录日志

param([string]$Path = './data/servers.csv')
$servers = Import-Csv -LiteralPath $Path
$total = 0
foreach ($s in $servers) {
    if ($s.Env -eq 'prod') {
        $total = $total + 1
    }
}
"prod servers: $total"
$script = (Resolve-Path ./scripts/Get-ProdSummary.ps1).Path
$null = Set-PSBreakpoint -Script $script -Line 6 -Action {
    Write-Host "line 6: server=$($s.Name) total=$total"
}
$null = Set-PSBreakpoint -Script $script -Variable total -Mode Write -Action {
    Write-Host "  `$total written, value now: $total"
}
$null = Set-PSBreakpoint -Command Import-Csv -Action { Write-Host "Import-Csv called: $($_.GetType().Name)" }
Get-PSBreakpoint | Format-Table Id, @{ n = 'Script'; e = { Split-Path $_.Script -Leaf } }, Line, Command, Variable, AccessMode -AutoSize
& $script
Get-PSBreakpoint | Format-Table Id, Line, Command, Variable, HitCount -AutoSize
Get-PSBreakpoint | Remove-PSBreakpoint
Id Script              Line Command    Variable AccessMode
-- ------              ---- -------    -------- ----------
 1 Get-ProdSummary.ps1    6                     
 2 Get-ProdSummary.ps1                 total    Write
 3                          Import-Csv          
Import-Csv called: CommandBreakpoint
  $total written, value now: 0
line 6: server=web-01 total=0
  $total written, value now: 1
line 6: server=web-02 total=1
  $total written, value now: 2
line 6: server=api-01 total=2
  $total written, value now: 3
line 6: server=edge-01 total=3
  $total written, value now: 4
line 6: server=db-01 total=4
  $total written, value now: 5
line 6: server=bastion-01 total=5
  $total written, value now: 6
prod servers: 6
Id Line Command    Variable HitCount
-- ---- -------    -------- --------
 1    6                            6
 2                 total           7
 3      Import-Csv                 1

如何验证:HitCount 显示行断点触发了 6 次(6 台 prod 服务器),变量断点 7 次(初始 $total = 0 加 6 次递增)。注意 Action 看到的是写入之后的值。常见错误:用 -Script ./x.ps1 设置断点,却通过另一个路径运行文件 —— 断点按解析后的完整路径匹配。生产用法:Action 断点是在服务器上给受变更管控的脚本加观测点的安全方式,无需修改文件。

2. 一次交互式会话(stdin 脚本化输入,真实输出)

$script = (Resolve-Path ./scripts/Get-ProdSummary.ps1).Path
$null = Set-PSBreakpoint -Script $script -Line 6
& $script
Entering debug mode. Use h or ? for help.

Hit Line breakpoint on 'C:\Users\labadmin\pslab\scripts\Get-ProdSummary.ps1:6'

At C:\Users\labadmin\pslab\scripts\Get-ProdSummary.ps1:6 char:9
+         $total = $total + 1
+         ~~~~~~~~~~~~~~~~~~~
[DBG]: PS C:\Users\labadmin\pslab>> l

    1:  param([string]$Path = './data/servers.csv')
    2:  $servers = Import-Csv -LiteralPath $Path
    3:  $total = 0
    4:  foreach ($s in $servers) {
    5:      if ($s.Env -eq 'prod') {
    6:*         $total = $total + 1
    7:      }
    8:  }
    9:  "prod servers: $total"

[DBG]: PS C:\Users\labadmin\pslab>> v
At C:\Users\labadmin\pslab\scripts\Get-ProdSummary.ps1:4 char:10
+ foreach ($s in $servers) {
+          ~~
[DBG]: PS C:\Users\labadmin\pslab>> $s.Name
web-01
[DBG]: PS C:\Users\labadmin\pslab>> $total
1
[DBG]: PS C:\Users\labadmin\pslab>> k

Command             Arguments Location
-------             --------- --------
Get-ProdSummary.ps1 {}        Get-ProdSummary.ps1: line 4
debug-prod.ps1      {}        debug-prod.ps1: line 3

[DBG]: PS C:\Users\labadmin\pslab>> c
Hit Line breakpoint on 'C:\Users\labadmin\pslab\scripts\Get-ProdSummary.ps1:6'
...
[DBG]: PS C:\Users\labadmin\pslab>> q
Entering debug mode. Use h or ? for help.

Hit Line breakpoint on 'C:\Users\labadmin\pslab\scripts\trace-demo.ps1:3'

At C:\Users\labadmin\pslab\scripts\trace-demo.ps1:3 char:1
+ $y = Get-Double $x
+ ~~~~~~~~~~~~~~~~~~
[DBG]: PS C:\Users\labadmin\pslab>> s
At C:\Users\labadmin\pslab\scripts\trace-demo.ps1:1 char:30
+ function Get-Double([int]$n) { $n * 2 }
+                              ~
[DBG]: PS C:\Users\labadmin\pslab>> s
At C:\Users\labadmin\pslab\scripts\trace-demo.ps1:1 char:32
+ function Get-Double([int]$n) { $n * 2 }
+                                ~~~~~~
[DBG]: PS C:\Users\labadmin\pslab>> $n
5
[DBG]: PS C:\Users\labadmin\pslab>> o
At C:\Users\labadmin\pslab\scripts\trace-demo.ps1:4 char:1
+ "y=$y"
+ ~~~~~~
[DBG]: PS C:\Users\labadmin\pslab>> $y
10
[DBG]: PS C:\Users\labadmin\pslab>> v
y=10

如何验证:在第 6 行按 v 后,调试器停在第 4 行(foreach 头),此时 $total 已经是 1。第二个会话中,s 进入 Get-Double,$n 为 5,o 返回调用方且 $y = 10。

3. Wait-Debugger

$servers = Import-Csv ./data/servers.csv
$prod = $servers | Where-Object Env -eq 'prod'
Wait-Debugger
"prod: $($prod.Count)"
Entering debug mode. Use h or ? for help.

At C:\Users\labadmin\pslab\scripts\wait-demo.ps1:3 char:1
+ Wait-Debugger
+ ~~~~~~~~~~~~~
[DBG]: PS C:\Users\labadmin\pslab>> $prod.Count
6
[DBG]: PS C:\Users\labadmin\pslab>> k

Command       Arguments Location
-------       --------- --------
wait-demo.ps1 {}        wait-demo.ps1: line 3

[DBG]: PS C:\Users\labadmin\pslab>> c
prod: 6

当 stdin 处于文件末尾时(pwsh -NonInteractive -File wait-demo.ps1 < /dev/null),同一脚本打印调试器横幅后在 0.7 秒内继续执行到 prod: 6;当 stdin 打开但无人输入时,它一直等待直到被终止。两种结果都不是生产环境想要的。

4. Set-PSDebug -Trace:PowerShell 的 set -x

function Get-Double([int]$n) { $n * 2 }
$x = 5
$y = Get-Double $x
"y=$y"
Set-PSDebug -Trace 2
& ./scripts/trace-demo.ps1
Set-PSDebug -Off
DEBUG:    2+  >>>> & ./scripts/trace-demo.ps1
DEBUG:    2+  >>>> $x = 5
DEBUG:     ! CALL function '<ScriptBlock>'  (defined in file 'C:\Users\labadmin\pslab\scripts\trace-demo.ps1')
DEBUG:     ! SET $x = '5'.
DEBUG:    3+  >>>> $y = Get-Double $x
DEBUG:    1+ function Get-Double([int]$n)  >>>> { $n * 2 }
DEBUG:     ! CALL function 'Get-Double'  (defined in file 'C:\Users\labadmin\pslab\scripts\trace-demo.ps1')
DEBUG:    1+ function Get-Double([int]$n) {  >>>> $n * 2 }
DEBUG:    1+ function Get-Double([int]$n) { $n * 2  >>>> }
DEBUG:     ! SET $y = '10'.
DEBUG:    4+  >>>> "y=$y"
y=10
DEBUG:    3+  >>>> Set-PSDebug -Off

-Trace 1 只打印 DEBUG: N+ >>>> … 行标记;-Trace 2 额外打印 ! CALL 和 ! SET。对 Get-ProdSummary.ps1 使用 -Trace 1,12 台服务器产生了 37 行跟踪 —— 短脚本还好,模块就太多了。

5. Set-PSDebug -Strict 与 Set-StrictMode

$servrs = Import-Csv ./data/servers.csv      # typo: $servrs
"in a string: $servers"
$servers.Count
Set-PSDebug -Strict
& ./scripts/strict-demo.ps1
Set-PSDebug -Off
in a string: 
InvalidOperation: C:\Users\labadmin\pslab\scripts\strict-demo.ps1:3
Line |
   3 |  $servers.Count
     |  ~~~~~~~~
     | The variable '$servers' cannot be retrieved because it has not been set.

如何验证:字符串内的引用("in a string: $servers")悄无声息地通过了 —— -Strict 等于严格模式 1.0,它豁免字符串。Set-StrictMode -Version Latest 还能捕获这种情况以及不存在的属性。生产用法:在每个脚本顶部和模块的 .psm1 中写 Set-StrictMode -Version Latest。

6. Write-Debug 与 -Debug

function Get-Total {
    [CmdletBinding()]
    param([int[]]$Value)
    Write-Debug "input count: $($Value.Count)"
    $sum = ($Value | Measure-Object -Sum).Sum
    Write-Debug "sum: $sum; DebugPreference=$DebugPreference"
    $sum
}
Get-Total -Value 1, 2, 3
Get-Total -Value 1, 2, 3 -Debug
$ExecutionContext.SessionState.LanguageMode
6
DEBUG: input count: 3
DEBUG: sum: 6; DebugPreference=Continue
6
FullLanguage

7. VS Code:.vscode/launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "PowerShell: Launch Current File",
      "type": "PowerShell",
      "request": "launch",
      "script": "${file}",
      "cwd": "${cwd}"
    },
    {
      "name": "PowerShell: Run OpsKit tests",
      "type": "PowerShell",
      "request": "launch",
      "script": "Invoke-Pester -Path ${workspaceFolder}/tests -Output Detailed",
      "cwd": "${workspaceFolder}"
    },
    {
      "name": "PowerShell: Attach to PowerShell Host Process",
      "type": "PowerShell",
      "request": "attach"
    }
  ]
}

这三种配置形式来自 PowerShell 扩展 package.json(2026.1.2)中的代码片段:“Launch Current File” 使用 ${file},“Launch Script” 接受路径或命令(这里用于 Invoke-Pester),“Attach” 选择一个正在运行的 pwsh 进程。F9 切换断点;右键断点可设置条件或命中次数。

目标:只用断点找出“统计 prod 服务器”的脚本为什么给出错误数字。环境:pwsh 7.6、~/pslab/data/servers.csv。费用:无。

创建一个有缺陷的副本 —— 它在错误的列上用 -like 计数:
Set-Location ~/pslab
@'
$servers = Import-Csv ./data/servers.csv
$total = 0
foreach ($s in $servers) {
    if ($s.Region -like 'ca*') { $total++ }
}
"prod servers: $total"
'@ | Set-Content ./scripts/buggy.ps1
./scripts/buggy.ps1
prod servers: 12
不改文件,记录每一次递增:
$bp = Set-PSBreakpoint -Script (Resolve-Path ./scripts/buggy.ps1) -Line 4 -Action {
    Write-Host "$($s.Name) $($s.Env) $($s.Region)"
}
./scripts/buggy.ps1 | Out-Null
Remove-PSBreakpoint $bp

你会在列表中看到 dev 和 staging 服务器 —— 错的是条件,不是计数器。

条件停止:只在统计到非 prod 服务器时停下并检查。
$bp = Set-PSBreakpoint -Script (Resolve-Path ./scripts/buggy.ps1) -Line 4 -Action {
    if ($s.Env -ne 'prod' -and $s.Region -like 'ca*') { break }
}
./scripts/buggy.ps1
# 在 [DBG] 下输入  $s | Format-List *   然后  q
改用跟踪:Set-PSDebug -Trace 1; ./scripts/buggy.ps1; Set-PSDebug -Off —— 数一数出现了多少行 DEBUG:。然后把第 4 行改为 if ($s.Env -eq 'prod'),确认输出 prod servers: 6。
VS Code:打开 buggy.ps1,在第 4 行的行号栏点击(F9),按 F5 选择 “PowerShell: Launch Current File”。把 $s.Env 加入 WATCH,反复按 F5。
清理:Get-PSBreakpoint | Remove-PSBreakpoint; Set-PSDebug -Off; Remove-Item ./scripts/buggy.ps1

案例 1:热修复之后夜间任务“卡死”

问题:一次紧急修复后,计划执行的 OpsKit 备份再也没有结束。根因:工程师排查时在脚本里留下了 Wait-Debugger;任务的 stdin 是一个打开的句柄,于是调试器永远等待。修复:删除它,在 CI 中加入检查 Select-String -Path ./**/*.ps1 -Pattern 'Wait-Debugger|Set-PSBreakpoint',命中即构建失败;并为计划任务设置运行时限。

案例 2:变量断点几分钟就找到作用域缺陷

问题:模块中的 $script:retryCount 有时为 0,本应是 3。根因:一个辅助函数在一处写了 $retryCount = 0(新建了局部变量),另一处写的是 $script:retryCount。发现方式:Set-PSBreakpoint -Variable retryCount -Mode Write -Action { Get-PSCallStack | Select-Object -First 2 | Out-String | Write-Host } 显示了两个写入方。这就是第 3 课的作用域规则在现场的表现。

案例 3:跟踪把机密泄露到构建日志

问题:为了排查不稳定的流水线,有人加了 Set-PSDebug -Trace 2。根因:! SET $token = 'eyJ…' 这样的行进入了公开日志。修复:绝不对处理机密的代码在 CI 中开启跟踪;使用经过脱敏、有意设计的 Write-Verbose 消息,并轮换泄露的令牌。

常见错误与修复

行断点从不触发

原因:脚本是通过不同路径运行的(相对路径与完整路径、符号链接、副本),或该行没有可执行语句(花括号、注释)。

Get-PSBreakpoint | Format-Table Id, Script, Line, HitCount
Set-PSBreakpoint -Script (Resolve-Path ./x.ps1).Path -Line 12
-Action 打印模块函数内部的变量时为空

原因(已在 7.6.10 上验证):Action 脚本块属于创建它的会话状态(你的控制台或脚本),因此看不到在模块内运行的函数的局部变量。对 OpsKit 的 Get-OpsServer 第 32 行设置的 Action 断点对每一行都打印 Monitored='' -> ,而普通断点的 [DBG] 提示符显示 $row.Name = web-01。修复:改用交互式停止,或在函数内部用 Write-Debug 记录。

调试器停在了我不关心的模块函数里

原因:命令断点(-Command Get-*)到处匹配。修复:加 -Script 限定范围,或用 v(单步跳过)代替 s。

VS Code:“The PowerShell extension's session is not running” / 断点是灰色的

原因:扩展连接的是 5.1,或启动失败。修复:点击状态栏中的版本号,选择 PowerShell 7.6,重启会话(命令面板 → “PowerShell: Restart Session”)。

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

原因:严格模式已开启,而变量拼错了或从未赋值 —— 这正是严格模式的用途。修复:改正变量名;对于可选变量,用 Test-Path Variable:x 检测或先初始化。

Write-Debug 没有输出 DEBUG: 行

原因:函数缺少 [CmdletBinding()],因此 -Debug 不是参数;或 $DebugPreference 为 SilentlyContinue。修复:加上 [CmdletBinding()] 并带 -Debug 调用。

命令行练习
1. 只在 Get-ProdSummary.ps1 第 3 次写入 $total 时停止。
$n = 0
Set-PSBreakpoint -Script (Resolve-Path ./scripts/Get-ProdSummary.ps1).Path -Variable total -Mode Write -Action {
    $script:n++; if ($script:n -eq 3) { break }
}

Action 在脚本作用域中运行,所以把计数器放在你能控制的作用域里(这里是调用方脚本的 $script:;在控制台中用 $global:n)。

2. 在一次运行中找出每一次 Remove-Item 调用并打印其参数,不停止。
New-Item -ItemType Directory ./tmp -Force | Out-Null; Set-Content ./tmp/a.txt 'a'
$null = Set-PSBreakpoint -Command Remove-Item -Action {
    $cs = Get-PSCallStack
    Write-Host "PSDebugContext null? $($null -eq $PSDebugContext)"
    $cs | ForEach-Object { Write-Host ("  frame: {0} | {1}" -f $_.Command, $_.Position.Text) }
}
Remove-Item -LiteralPath ./tmp/a.txt
Get-PSBreakpoint | Remove-PSBreakpoint
Remove-Item ./tmp -Recurse
PSDebugContext null? True
  frame:  | $cs = Get-PSCallStack
  frame: d9.ps1 | Remove-Item -LiteralPath ./tmp/a.txt

在 -Action 中 $PSDebugContext 为 $null(已验证)—— 它只在真正的 [DBG] 停止时存在。Get-PSCallStack 可用:第 1 帧就是调用所在的那一行。

场景分析
一个健康检查手动运行正常,但在 02:00 的计划运行中把所有服务器都报告为宕机。你无法交互式复现。怎么办?

不要把调试器附加到计划运行上,而是收集证据:用 Start-Transcript、-Verbose 运行任务,必要时临时加一个带 -Action 的断点记录 Test-OpsEndpoint 的输入(不涉及机密时也可用 Set-PSDebug -Trace 1)。然后在本地复现相同条件:相同账号(runas)、pwsh -NoProfile -NonInteractive -File、相同的代理/DNS。典型根因:服务账号没有代理设置、相对路径被解析到 System32、或依赖配置文件中加载的模块(第 1 课)。

已验证的教学视频

▶
Debug PowerShell with and without VS Code — John Savill's Technical Training
英文 · 控制台调试器与 VS Code 对照
▶
Debugging PowerShell Scripts in Visual Studio Code — Adam Driscoll
英文 · VS Code 中的断点、单步与变量
▶
Set Line, Variable, Function, Conditional Breakpoints in PowerShell Scripts — SAPIEN Technologies
英文 · Set-PSBreakpoint 的各种断点类型
▶
Advanced PowerShell Debugging Techniques — Adam Driscoll
英文 · 作业、运行空间与远程调试

官方文档

视频分镜(约 90 秒)

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

镜头 1 · 0–20 秒
画面:一个满是 Write-Host "x=$x" 的脚本,这些行被逐一删除;第 6 行出现一个红点。
旁白:别再猜了 —— 让脚本停在出错的地方。
镜头 2 · 20–55 秒
画面:[DBG] 提示符;光标在代码中移动时,s、v、o、c 键依次亮起;按 k 时调用栈滑入。
旁白:进入、跳过、跳出、继续 —— 在提示符下可以问任何问题。
镜头 3 · 55–75 秒
画面:一个带闪电图标(Action)的断点在脚本继续运行时打印日志行。
旁白:Action 断点就是一行不需要动文件的日志。
镜头 4 · 75–90 秒
画面:一个卡在 Wait-Debugger 上的计划任务,随后 CI 检查拒绝了这次提交。
旁白:绝不要把断点带上线;无人值守运行用跟踪和日志。
或测验得分 ≥ 70%

模块 2 · 静态分析:PSScriptAnalyzer 规则、配置、抑制与格式化

06:00 – 13:00 · PSScriptAnalyzer 不运行代码就能读懂它,标出别名、明文密码、空 catch 块、未认可的动词以及几十类其他问题 —— 相当于 PowerShell 版的 ShellCheck
7 分钟Invoke-ScriptAnalyzer · Invoke-Formatter★★★★☆
学习目标
  • 对文件、文件夹(-Recurse)或字符串(-ScriptDefinition)运行 Invoke-ScriptAnalyzer,读懂 RuleName、Severity、Line。
  • 了解三种严重级别(Error、Warning、Information)各有多少规则,以及哪些常见规则属于 Error。
  • 用 PSScriptAnalyzerSettings.psd1 控制分析 —— 并且知道放在被分析路径旁、文件名完全一致的配置会被自动使用,并覆盖 -Severity。
  • 用带理由的 [Diagnostics.CodeAnalysis.SuppressMessageAttribute()] 抑制单条告警;用 Invoke-Formatter 修正布局,用 -Fix 修正别名。
前置条件:模块 0(PSScriptAnalyzer 1.25.0)。重要度:★★★★☆(你能加上的最便宜的质量门禁)

是什么:在语法树上运行的规则

PSScriptAnalyzer(PSSA)把脚本解析成与引擎相同的 AST,再让每条规则在 AST 上运行。它不执行任何代码,因此对不可信代码也是安全的,而且快到可以每次按键都运行 —— VS Code 扩展正是这样做的。1.25.0 版共有 75 条规则:8 条 Error、56 条 Warning、11 条 Information(在实验机上用 Get-ScriptAnalyzerRule 统计)。

规则(示例)严重级别为什么重要
PSAvoidUsingConvertToSecureStringWithPlainTextError机密出现在脚本或历史记录中
PSAvoidUsingPlainTextForPasswordWarning[string]$Password 参数:应使用 [securestring] 或 [pscredential]
PSAvoidUsingCmdletAliasesWarninggci、%:难读,且不同平台不一致(第 1 课)
PSAvoidUsingWriteHostWarning输出无法被捕获为数据(使用 Show 动词的函数除外)
PSUseApprovedVerbsWarningFetch-Servers → Get-OpsServer;模块导入时会警告
PSAvoidUsingEmptyCatchBlockWarning吞掉错误(第 5 课)
PSPossibleIncorrectComparisonWithNullWarning$rows -eq $null 会过滤数组;应写 $null -eq $rows
PSUseDeclaredVarsMoreThanAssignmentsWarning只赋值从不使用:死代码或拼写错误
PSUseShouldProcessForStateChangingFunctionsWarningSet-/Remove-/New- 函数缺少 SupportsShouldProcess
PSAvoidUsingPositionalParametersInformation只针对可解析的命令且有 3 个及以上位置参数(已验证)

为什么:白捡的问题发现

上表中每一条都是你不用再在代码评审中手动指出的缺陷或意见。在 CI 中,PSSA 成为一道门禁:“模块代码中不允许有 Error 或 Warning”。它还能强制格式(花括号位置、缩进、大小写),让 diff 只显示逻辑而不是空白。

怎么做:配置决定运行什么

配置项含义
Severity = @('Error','Warning')只报告这些级别
IncludeRules / ExcludeRules规则名的允许列表 / 排除列表(支持通配符)
IncludeDefaultRules = $true同时配置额外规则时保留默认规则集
Rules = @{ PSPlaceOpenBrace = @{ Enable = $true; OnSameLine = $true } }启用可配置规则(格式化、PSUseCompatibleSyntax、PSUseCompatibleCommands)
内置预设-Settings PSGallery、CodeFormatting、CodeFormattingOTBS、CodeFormattingStroustrup、CodeFormattingAllman

何时用:编辑器中、提交前、CI 中

编辑器:VS Code 扩展实时运行 PSSA(从 powershell.scriptAnalysis.settingsPath 读取配置路径)。提交前:Invoke-ScriptAnalyzer -Path . -Recurse。CI 中:build.ps1 的 Analyze 任务让构建失败(模块 8)。只在写明理由时才抑制 —— 抑制和其他代码一样要经过评审。

常见误区① “-Severity Error 总能把输出限制为错误” —— 如果被分析路径旁有 PSScriptAnalyzerSettings.psd1 就不行:它会被自动加载,其 Severity 生效(1 条与 10 条,已验证)。② “没有告警就说明代码正确” —— PSSA 检查风格和已知反模式,不检查行为;那是 Pester 的工作。③ “Write-Host 总会被标记” —— 使用 Show 动词的函数被豁免(已验证)。④ “位置参数总会被标记” —— 只有对 PSSA 能解析的命令传入三个及以上位置参数才会。⑤ “抑制就是掩盖问题” —— 带理由的抑制记录了一个有意的决定;用 -IncludeSuppressed 审计它们。

图解:从源码到 CI 判定

.ps1 / .psm1或 -ScriptDefinition 解析器 → AST+ 词法单元 配置-Settings 文件 / 预设或 PSScriptAnalyzerSettings.psd1位于 -Path 旁(自动加载) 规则75 条内置+ 自定义规则在 AST 上运行 过滤严重级别包含/排除抑制 DiagnosticRecord 对象RuleName · Severity · Line · Message · SuggestedCorrections→ 给人看用 Format-Table · 给 CI 计数(> 0 即构建失败)-Fix 就地应用 SuggestedCorrections Invoke-Formatter同一引擎,只用格式化规则返回格式化后的文本(是否写回由你决定)
图 2-1:分析结果只取决于源码 + 配置;结果是对象,所以 CI 可以计数

分析器流水线:什么会进入报告?

每个场景跟踪一次对 scripts/bad.ps1 的 Invoke-ScriptAnalyzer 运行;日志显示 7.6.10 上真实的结果数量。

就绪。
动画背后的真实机制 Invoke-ScriptAnalyzer 先解析配置(显式的 -Settings,否则在被分析路径处查找 PSScriptAnalyzerSettings.psd1),确定规则集,解析文件,运行每条规则生成 DiagnosticRecord 对象,丢弃被严重级别过滤或被 SuppressMessageAttribute 覆盖的记录,其余写入管道。

命令表

命令用途说明
Invoke-ScriptAnalyzer -Path x.ps1分析文件文件夹用 -Recurse
Invoke-ScriptAnalyzer -ScriptDefinition $code分析字符串适合快速试验
-Severity Error, Warning过滤会被配置文件中的 Severity 覆盖
-IncludeRule / -ExcludeRule挑选规则支持通配符
-Settings ./PSScriptAnalyzerSettings.psd1使用配置文件或预设名提交到代码仓库
-Fix就地应用建议的修正会改写文件:先提交
-IncludeSuppressed同时显示被抑制的记录IsSuppressed 列
Get-ScriptAnalyzerRule列出规则-Name、-Severity
Invoke-Formatter -ScriptDefinition $code -Settings …格式化文本返回字符串

1. 一个故意写坏的脚本

function Fetch-Servers {
    param([string]$Path, [string]$Password)
    $secure = ConvertTo-SecureString $Password -AsPlainText -Force
    $unused = 'never read'
    $rows = gci $Path | % { Import-Csv $_.FullName }
    if ($rows -eq $null) { Write-Host 'no rows' }
    try {
        $rows | Where-Object { $_.Env -eq 'prod' }
    }
    catch {
    }
}
Fetch-Servers ./data 'P@ssw0rd!'
Join-Path $HOME 'pslab' 'tmp'
Import-Module PSScriptAnalyzer
Invoke-ScriptAnalyzer -Path ./scripts/bad.ps1 | Sort-Object Line |
    Format-Table Line, Severity, RuleName -AutoSize
'---'
Invoke-ScriptAnalyzer -Path ./scripts/bad.ps1 | Group-Object Severity -NoElement | Format-Table Count, Name -AutoSize
'---'
Get-ScriptAnalyzerRule | Group-Object Severity -NoElement | Format-Table Count, Name -AutoSize
@(Get-ScriptAnalyzerRule).Count
Line    Severity RuleName
----    -------- --------
   1     Warning PSUseApprovedVerbs
   1     Warning PSUseSingularNouns
   2     Warning PSAvoidUsingPlainTextForPassword
   3       Error PSAvoidUsingConvertToSecureStringWithPlainText
   3     Warning PSUseDeclaredVarsMoreThanAssignments
   4     Warning PSUseDeclaredVarsMoreThanAssignments
   5     Warning PSAvoidUsingCmdletAliases
   5     Warning PSAvoidUsingCmdletAliases
   6     Warning PSAvoidUsingWriteHost
   6     Warning PSPossibleIncorrectComparisonWithNull
  10     Warning PSAvoidUsingEmptyCatchBlock
  14 Information PSAvoidUsingPositionalParameters

---

Count Name
----- ----
    1 Information
   10 Warning
    1 Error

---

Count Name
----- ----
   11 Information
   56 Warning
    8 Error

75

如何验证:第 13 行(Fetch-Servers ./data 'P@ssw0rd!',对未知函数传两个位置参数)没有被标记,第 14 行(Join-Path 传三个)被标记了。第 3 行同时有一条 Error(明文 ConvertTo-SecureString)和一条 Warning($secure 从未使用)。常见错误:永远把 Information 当噪音;生产用法:CI 对 Error + Warning 设门禁,偶尔回顾 Information。

2. 单条规则详情

Import-Module PSScriptAnalyzer
$code = @'
Join-Path $HOME pslab data
Get-ChildItem ./data *.csv
Copy-Item ./a.txt ./b.txt
Fetch-Servers ./data P@ss extra
'@
Invoke-ScriptAnalyzer -ScriptDefinition $code -IncludeRule PSAvoidUsingPositionalParameters | Format-List Line, Message
Get-ScriptAnalyzerRule -Name PSAvoidUsingPositionalParameters | Format-List Severity, Description
Invoke-ScriptAnalyzer -Path ./scripts/bad.ps1 -IncludeRule PSAvoidUsingEmptyCatchBlock | Format-List *
Line    : 1
Message : Cmdlet 'Join-Path' has positional parameter. Please use named parameters instead of positional parameters 
          when calling a command.


Severity    : Information
Description : Readability and clarity should be the goal of any script we expect to maintain over time. When calling a 
              command that takes parameters, where possible consider using named parameters as opposed to positional 
              parameters. To fix a violation of this rule, please use named parameters instead of positional 
              parameters when calling a command.


Line                 : 10
Column               : 5
Message              : Empty catch block is used. Please use Write-Error or throw statements in catch blocks.
Extent               : catch {
                           }
RuleName             : PSAvoidUsingEmptyCatchBlock
Severity             : Warning
ScriptName           : bad.ps1
ScriptPath           : C:\Users\labadmin\pslab\scripts\bad.ps1
RuleSuppressionID    : 
SuggestedCorrections : 
IsSuppressed         : False

3. 配置文件 —— 以及自动加载

@{
    Severity     = @('Error', 'Warning')
    ExcludeRules = @('PSUseSingularNouns')
    Rules        = @{
        PSUseCompatibleSyntax = @{
            Enable         = $true
            TargetVersions = @('7.4', '5.1')
        }
        PSPlaceOpenBrace      = @{ Enable = $true; OnSameLine = $true }
        PSUseConsistentIndentation = @{ Enable = $true; IndentationSize = 4; Kind = 'space' }
    }
}
Import-Module PSScriptAnalyzer
$found = Invoke-ScriptAnalyzer -Path ./scripts/bad.ps1 -Severity Error
$found | Format-Table Line, Severity, RuleName -AutoSize
"errors: $(@($found).Count)"
Copy-Item ./settings/PSScriptAnalyzerSettings.psd1 ./scripts/
$found = Invoke-ScriptAnalyzer -Path ./scripts/bad.ps1 -Severity Error
"with PSScriptAnalyzerSettings.psd1 next to the script: $(@($found).Count)"
Remove-Item ./scripts/PSScriptAnalyzerSettings.psd1
'--- explicit settings'
Invoke-ScriptAnalyzer -Path ./scripts/bad.ps1 -Settings ./settings/PSScriptAnalyzerSettings.psd1 | Sort-Object Line | Format-Table Line, Severity, RuleName -AutoSize
Line Severity RuleName
---- -------- --------
   3    Error PSAvoidUsingConvertToSecureStringWithPlainText

errors: 1
with PSScriptAnalyzerSettings.psd1 next to the script: 10
--- explicit settings

Line Severity RuleName
---- -------- --------
   1  Warning PSUseApprovedVerbs
   2  Warning PSAvoidUsingPlainTextForPassword
   3    Error PSAvoidUsingConvertToSecureStringWithPlainText
   3  Warning PSUseDeclaredVarsMoreThanAssignments
   4  Warning PSUseDeclaredVarsMoreThanAssignments
   5  Warning PSAvoidUsingCmdletAliases
   5  Warning PSAvoidUsingCmdletAliases
   6  Warning PSAvoidUsingWriteHost
   6  Warning PSPossibleIncorrectComparisonWithNull
  10  Warning PSAvoidUsingEmptyCatchBlock

如何验证:同样的 -Severity Error 调用,没有配置文件时返回 1 条记录,脚本旁有 PSScriptAnalyzerSettings.psd1 时返回 10 条 —— 文件中的 Severity = Error, Warning 替换了参数。使用显式 -Settings 时,PSUseSingularNouns 消失了(被排除),Information 记录也消失了(被级别过滤)。生产用法:在仓库根目录只保留一个配置文件,并在 CI 中始终显式传 -Settings,让行为不依赖当前目录。

4. 带理由的抑制

function Invoke-Banner {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Interactive banner only; not data.')]
    [CmdletBinding()]
    param()
    Write-Host 'OpsKit 1.0' -ForegroundColor Cyan
}
function Get-Usage {
    Write-Host 'usage: ...'
}
Import-Module PSScriptAnalyzer
Invoke-ScriptAnalyzer -Path ./scripts/suppress.ps1 | Format-Table Line, RuleName -AutoSize
Invoke-ScriptAnalyzer -Path ./scripts/suppress.ps1 -IncludeSuppressed | Format-Table Line, RuleName, IsSuppressed -AutoSize
Line RuleName
---- --------
   8 PSAvoidUsingWriteHost


Line RuleName              IsSuppressed
---- --------              ------------
   8 PSAvoidUsingWriteHost        False
   5 PSAvoidUsingWriteHost         True

该特性放在函数上、[CmdletBinding()] 之前,只对这个函数生效。第二个参数('')可以指定具体的 RuleSuppressionID;文件级抑制可使用 -Scope Function -Target 'Name*' 形式。

5. Invoke-Formatter 与 -Fix

Import-Module PSScriptAnalyzer
Invoke-ScriptAnalyzer -Path ./scripts/bad.ps1 -Settings ./settings/PSScriptAnalyzerSettings.psd1 |
    Format-Table Line, Severity, RuleName -AutoSize
'--- formatter'
$ugly = @'
function Get-X{
param($a)
if($a){
"yes"}
else {  "no" }
}
'@
Invoke-Formatter -ScriptDefinition $ugly
'--- fix'
Copy-Item ./scripts/bad.ps1 ./tmp-fix.ps1
Invoke-ScriptAnalyzer -Path ./tmp-fix.ps1 -Fix | Out-Null
Get-Content ./tmp-fix.ps1 | Select-Object -Index 4
Remove-Item ./tmp-fix.ps1
'--- exit-code style'
$errors = Invoke-ScriptAnalyzer -Path ./scripts/bad.ps1 -Severity Error
"errors: $(@($errors).Count)"
Line Severity RuleName
---- -------- --------
  10  Warning PSAvoidUsingEmptyCatchBlock
   3    Error PSAvoidUsingConvertToSecureStringWithPlainText
   6  Warning PSAvoidUsingWriteHost
   2  Warning PSAvoidUsingPlainTextForPassword
   6  Warning PSPossibleIncorrectComparisonWithNull
   1  Warning PSUseApprovedVerbs
   3  Warning PSUseDeclaredVarsMoreThanAssignments
   4  Warning PSUseDeclaredVarsMoreThanAssignments
   5  Warning PSAvoidUsingCmdletAliases
   5  Warning PSAvoidUsingCmdletAliases

--- formatter
function Get-X {
    param($a)
    if ($a) {
        "yes"
    }
    else { "no" }
}
--- fix
    $rows = Get-ChildItem $Path | ForEach-Object { Import-Csv $_.FullName }
--- exit-code style
errors: 1

-Fix 在副本中把 gci 和 % 替换成了 Get-ChildItem 和 ForEach-Object;位置参数和空 catch 需要人来修。最后一行是 CI 风格的计数:附近没有配置文件时,-Severity Error 得到 1。

目标:把 scripts/bad.ps1 清理到 0 条 Error 和 Warning。环境:pwsh 7.6、PSScriptAnalyzer 1.25.0。费用:无。

基线:运行 Invoke-ScriptAnalyzer ./scripts/bad.ps1 | Sort-Object Line | Format-Table Line, Severity, RuleName 并数一数记录(没有配置文件时为 12 条)。
能自动修的先自动修:Copy-Item ./scripts/bad.ps1 ./scripts/good.ps1; Invoke-ScriptAnalyzer ./scripts/good.ps1 -Fix | Out-Null。
其余手动修正 —— 参考答案:
function Get-ProdServer {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Path,

        [Parameter(Mandatory)]
        [pscredential]$Credential
    )
    $rows = Get-ChildItem -Path $Path -Filter '*.csv' | ForEach-Object { Import-Csv -LiteralPath $_.FullName }
    if ($null -eq $rows) {
        Write-Warning 'no rows'
        return
    }
    try {
        $rows | Where-Object { $_.Env -eq 'prod' }
    } catch {
        Write-Error -ErrorRecord $_
    }
}
门禁:
$found = Invoke-ScriptAnalyzer ./scripts/good.ps1 -Settings ./settings/PSScriptAnalyzerSettings.psd1
"findings: $(@($found).Count)"; if ($found) { exit 1 }
findings: 0
格式化:故意打乱缩进,然后运行 Invoke-Formatter -ScriptDefinition (Get-Content ./scripts/good.ps1 -Raw) -Settings CodeFormattingOTBS 并对比。
清理:Remove-Item ./scripts/good.ps1

案例 1:“本地分析通过,CI 却失败”

问题:开发者运行 Invoke-ScriptAnalyzer -Path ./src -Recurse -Severity Error 看不到任何告警;CI 却因 Warning 失败。根因:CI 从仓库根目录运行,那里的 PSScriptAnalyzerSettings.psd1(Severity Error, Warning)被自动加载;本地则是在 src 中运行。修复:只用一个配置文件,并在开发者和 CI 共用的构建脚本中始终用 -Settings 传入。

案例 2:合并进来的脚本里有明文密码

问题:一个包含 ConvertTo-SecureString 'Winter2026!' -AsPlainText -Force 的脚本被合并,密码进入了 Git 历史。修复:轮换机密,改从 SecretManagement 或 CI 机密获取(第 7 课),并让 PSSA 的 Error 阻止拉取请求合并。在后续提交中删除这一行并不能把它从历史中移除。

案例 3:格式噪音淹没了真正的改动

问题:一个只改了一个条件的拉取请求显示 400 行变更,因为编辑器重新缩进了整个文件。修复:约定一个格式预设(CodeFormattingOTBS 或配置文件),在单独的“仅格式化”提交中运行一次 Invoke-Formatter,之后在 CI 中强制布局规则。

常见错误与修复

Invoke-ScriptAnalyzer: The term 'Invoke-ScriptAnalyzer' is not recognized

原因:模块没有为 pwsh 7 安装(或只在不在 PSModulePath 上的随项目目录中)。

Get-Module PSScriptAnalyzer -ListAvailable
Install-PSResource PSScriptAnalyzer -Version 1.25.0 -Scope CurrentUser
VS Code 与命令行结果不同

原因:扩展使用自带的 PSSA 版本和自己的配置路径。修复:在 .vscode/settings.json 中设置 "powershell.scriptAnalysis.settingsPath": "PSScriptAnalyzerSettings.psd1",并比较 (Get-Module PSScriptAnalyzer).Version。

SuppressMessageAttribute 不生效

原因:规则名错误(必须是确切的 RuleName,如 PSAvoidUsingWriteHost),或者特性没有放在包含该告警的函数/param 块上。

大型仓库分析非常慢

原因:兼容性规则(PSUseCompatibleCommands)要加载大型配置文件;或分析了 node_modules、构建输出。修复:只分析源码目录,兼容性规则只在 CI 中启用。

命令行练习
1. 列出 PSSA 1.25.0 中所有 Error 级别的规则。
Get-ScriptAnalyzerRule -Severity Error | Sort-Object RuleName | Select-Object RuleName
2. 如果任何模块文件有 Error 或 Warning,先打印表格再让流水线步骤失败。
$r = Invoke-ScriptAnalyzer -Path ./OpsKit -Recurse -Settings ./OpsKit/PSScriptAnalyzerSettings.psd1
$r | Format-Table Severity, RuleName, ScriptName, Line -AutoSize
exit [int]([bool]$r)
场景分析
团队想在一个有 300 个脚本、当前有 2,400 条告警的仓库中引入 PSSA。如何推进而不让所有人被阻塞?

① 提交一个配置文件。② 在专门的机械性提交中运行 -Fix 和 Invoke-Formatter(易于评审,也易于回滚)。③ 立即对 Error 设门禁(通常数量少,且与安全相关)。④ 对 Warning 只在拉取请求的变更文件上设门禁(git diff --name-only → Invoke-ScriptAnalyzer)。⑤ 每周跟踪总数直到归零,然后全面设门禁。抑制在评审中必须附理由。

已验证的教学视频

▶
PowerShell+ 2019 - PSScriptAnalyzer (PSSA) VS-code integration & ... by Christoph Bergmeister — Confreaks
英文 · PSScriptAnalyzer 维护者讲解编辑器集成与规则配置
▶
PolarConf 2018: PowerShell Script Analyzer: Good, consistent and pretty code by Jeff Wouters — Finland Azure User Group
英文 · 为什么一致的风格和分析很重要
▶
A Crash Course in Writing Your Own PSScriptAnalyzer Rules by Thomas Rayner — PowerShell.org
英文 · 超出本课范围:自定义规则

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–20 秒
画面:bad.ps1 上逐一出现 12 条波浪线,每条对应一个告警,按严重级别着色。
旁白:PSScriptAnalyzer 不运行代码就能读懂它。
镜头 2 · 20–50 秒
画面:一个配置文件滑到脚本旁边;-Severity Error 过滤器被划掉。
旁白:路径旁的配置文件会被自动使用 —— 请显式传入 -Settings。
镜头 3 · 50–75 秒
画面:一个高亮了“Justification:”的特性;IsSuppressed 为 True。
旁白:在问题发生的地方、带着理由抑制一条告警。
镜头 4 · 75–90 秒
画面:CI 检查因一条 Warning 变红,修复后变绿。
旁白:让分析器成为门禁,而不是建议。
或测验得分 ≥ 70%

模块 3 · Pester 基础:Describe / Context / It、Should-* 断言与 TestDrive

13:00 – 21:00 · Pester 测试文件就是一个 PowerShell 脚本,Pester 会运行它两次:一次发现测试,一次运行测试。理解了这两个阶段,测试块、前置初始化、断言、临时目录、数据驱动测试就都顺理成章了
8 分钟Pester 6.2.0★★★★★
学习目标
  • 用 BeforeAll、Describe、Context、It、BeforeEach、AfterEach、AfterAll 组织测试文件。
  • 解释发现(Discovery)与运行(Run)阶段,并复现经典缺陷:写在文件顶部或直接写在 Describe 中的代码在发现阶段执行,等到 It 运行时变量已经不在了。
  • 使用 Pester 6 的 Should-* 系列(Should-Be、Should-BeString、Should-BeCollection、Should-BeEquivalent、Should-Throw 等),并知道它与经典 Should -Be 的差异。
  • 用 TestDrive: / $TestDrive 隔离文件系统测试,用 -ForEach 和 <Name> 模板根据数据生成测试。
前置条件:模块 0。重要度:★★★★★(模块 4、5、8 的基础)

是什么:各个测试块及其职责

关键字职责执行阶段
Describe 'Get-OpsServer' { }为一个单元(通常是一个函数)分组测试块体:发现阶段
Context 'with filters' { }针对某一情形的子分组;有自己的前置初始化和 TestDrive 范围块体:发现阶段
It 'returns 12 servers' { }一个测试:准备、执行、断言在发现阶段注册,块体在运行阶段执行
BeforeAll { } / AfterAll { }每个块(或位于顶层时每个文件)执行一次:导入模块、构建测试数据运行阶段
BeforeEach { } / AfterEach { }在块及其子块中每个 It 前后执行:重置状态、设置 Mock运行阶段
BeforeDiscovery { }计算 -ForEach 需要的数据发现阶段

Pester 6.2 允许在同一个块中写多个 BeforeAll/AfterAll/BeforeEach/AfterEach(6.0 遇到重复会抛错;6.2 按书写顺序执行,清理块逆序执行 —— 见 6.2.0 发布说明)。

为什么:两个阶段

Pester 先以发现模式执行文件:运行 Describe/Context 的块体来构建测试树,但不运行 It 块体和 Before* 块。这样就能在任何东西运行之前完成过滤(-TagFilter、-FullNameFilter)、统计测试数量和展开数据驱动测试。随后运行阶段遍历测试树,在各自的作用域中运行前置初始化、测试和清理。从 Pester 6 开始,发现与运行按文件进行:文件 A 发现并运行完之后才发现文件 B,因此发现阶段的副作用不再在文件之间泄漏。

规则:测试运行时需要的一切都放在 BeforeAll/BeforeEach 或 It 本身中。只有 -ForEach 的数据属于发现阶段。

怎么做:两种断言语法

经典语法(Pester 4/5,6 中仍可用)Pester 6 新语法
相等$x | Should -Be 5$x | Should-Be 5(由 -Expected 的类型决定比较方式)
字符串Should -BeExactly、-BeLike、-MatchShould-BeString -CaseSensitive、-TrimWhitespace、-NormalizeLineEnding;Should-BeLikeString、Should-MatchString
布尔 / nullShould -BeTrue、-BeNullOrEmptyShould-BeTrue、Should-BeFalse、Should-BeNull、Should-BeTruthy
集合Should -Contain、-HaveCountShould-BeCollection(元素相同,顺序任意)、Should-ContainCollection、Should-All、Should-Any
对象—Should-BeEquivalent(深度比较,显示属性差异)、-ExcludePath、-ExcludePathsNotOnExpected
异常{ … } | Should -Throw -ExpectedMessage '…'{ … } | Should-Throw -ExceptionMessage '…' -ExceptionType ([…])(消息用 -like 匹配)
MockShould -InvokeShould-Invoke、Should-NotInvoke(模块 4)
关闭旧语法$config.Should.DisableV5 = $true 会让 Should -Be 抛错 —— 适合在测试套件迁移完成后使用

何时用:TestDrive 与 -ForEach

$TestDrive(也就是 TestDrive: 驱动器)是每个 Describe/Context 创建、结束后删除的临时目录 —— 测试写的每个文件都应放在这里。It、Context 或 Describe 上的 -ForEach 接受一个哈希表数组;每个键都会成为变量,也可在名称中作为 <key> 模板。在 Pester 6 中,空数组或 $null 的 -ForEach 会导致发现失败,除非加上 -AllowNullOrEmptyForEach(已验证)。

常见误区① “测试文件顶部的代码会在测试前运行” —— 它在发现阶段运行;到运行阶段时变量已不存在(已复现:Expected [int] 12, but got [int] 0)。② “Should-BeCollection 会检查顺序” —— 不会:'web','api' | Should-BeCollection @('api','web') 通过了;顺序重要时请比较 -join 后的字符串。③ “Should-Be 就是去掉空格的 Should -Be” —— 通过管道传入的 @() 会变成 $null,由 -Expected 决定类型转换,失败消息也不同。④ “每个 It 之间 TestDrive 会被清空” —— 它在整个 Describe/Context 期间都存在;请在 BeforeEach 中创建唯一子目录。⑤ “Import-Module Pester 一定是 Pester 6” —— 如果 3.4.0 排在前面就不是(模块 0)。

图解:一个测试文件,两次执行

Get-OpsServer.Tests.ps1 Import-Module … ← 顶层(D) BeforeAll { Import-Module; $csv }(R) Describe 'Get-OpsServer' {(D) $x = 1 ← 块体(只在 D!) Context 'with filters' {(D) BeforeEach { … }(R) It '<Env>' -ForEach @(…)(D:展开) { 块体 }(R) } } D = 发现阶段 · R = 运行阶段 第 1 遍:发现执行顶层代码和块体注册 It / Before*(不运行)展开 -ForEach(2 个测试)应用过滤(标签、名称)→ 测试树 第 2 遍:运行BeforeAll(文件、块)每个 It:BeforeEach → It → AfterEachAfterAll新作用域;发现阶段的变量不在了每个 Describe/Context 一个 TestDrive Pester 6:按文件 Running tests from 9 files. 文件 1:发现 → 运行 文件 2:发现 → 运行 … v5 先发现所有文件, 再统一运行;一个文件发现 阶段的副作用可能泄漏 到下一个文件。 每个文件必须自行导入 所需内容(Run.BeforeContainer 或 Pester.BeforeContainer.ps1)
图 3-1:左侧代码标出了每行在哪个阶段执行;D 行中设置的变量在 R 行中不可见

核心动画:发现与运行,逐步演示

选择一种测试文件布局,观察每部分在哪一遍执行。红色表示测试出错的地方;日志显示 Pester 6.2.0 的真实输出。

就绪。
动画背后的真实机制 Invoke-Pester 为每个文件创建一个容器,并以“发现”模式点源执行该文件:Describe/Context 立即调用其脚本块以收集子项,而 It、BeforeAll 等只保存它们的脚本块。过滤之后,运行阶段在容器的新子作用域中调用保存的脚本块 —— 这就是为什么 Describe 块体中赋值的变量在 It 中不可见,而 BeforeAll 中赋值的变量可见。

命令表

命令用途说明
Invoke-Pester -Path ./tests -Output Detailed运行测试,每个测试一行-Output:None、Normal、Detailed、Diagnostic
Invoke-Pester -FullNameFilter '*retries*'只运行匹配的测试还有 -TagFilter、-ExcludeTagFilter('None' = 无标签的测试)
It 'x' -Tag 'slow'、-Skip给测试打标签 / 跳过测试内可用 Set-ItResult -Skipped -Because '…'(6 中没有 -Pending)
Get-Command -Module Pester -Name 'Should-*'列出新断言6.2.0 中有 41 个
$TestDrive、TestDrive:\每个块的临时目录块结束后删除
It '<Env>: <Count>' -ForEach @(@{Env='dev';Count=2})数据驱动测试键会成为变量

Pester 6.2.0 中的 41 个 Should-* 命令

Should-All, Should-Any, Should-Be, Should-BeAfter, Should-BeBefore, Should-BeCollection, Should-BeEmptyString, Should-BeEquivalent, Should-BeFalse, Should-BeFalsy, Should-BeFasterThan, Should-BeGreaterThan, Should-BeGreaterThanOrEqual, Should-BeHashtable, Should-BeLessThan, Should-BeLessThanOrEqual, Should-BeLikeString, Should-BeNull, Should-BeSame, Should-BeSlowerThan, Should-BeString, Should-BeTrue, Should-BeTruthy, Should-ContainCollection, Should-HaveParameter, Should-HaveType, Should-Invoke, Should-MatchString, Should-NotBe, Should-NotBeEmptyString, Should-NotBeLikeString, Should-NotBeNull, Should-NotBeSame, Should-NotBeString, Should-NotBeWhiteSpaceString, Should-NotContainCollection, Should-NotHaveParameter, Should-NotHaveType, Should-NotInvoke, Should-NotMatchString, Should-Throw

1. 复现发现阶段缺陷

Import-Module "$PSScriptRoot/../OpsKit/OpsKit.psd1" -Force   # runs at DISCOVERY
$servers = Get-OpsServer -Path "$PSScriptRoot/../data/servers.csv"  # runs at DISCOVERY

Describe 'Get-OpsServer (broken setup)' {
    It 'returns 12 servers' {
        $servers.Count | Should-Be 12
    }
}
BeforeAll {
    Import-Module "$PSScriptRoot/../OpsKit/OpsKit.psd1" -Force
    $servers = Get-OpsServer -Path "$PSScriptRoot/../data/servers.csv"
}

Describe 'Get-OpsServer (fixed setup)' {
    It 'returns 12 servers' {
        $servers.Count | Should-Be 12
    }
}
Import-Module Pester -MinimumVersion 6.0.0
Invoke-Pester -Path ./demo/Discovery.Tests.ps1, ./demo/DiscoveryFixed.Tests.ps1 -Output Detailed
Pester v6.2.0

Running tests from 2 files.

Running tests from 'C:\Users\labadmin\pslab\demo\Discovery.Tests.ps1'
Describing Get-OpsServer (broken setup)
  [-] returns 12 servers 184ms
   Expected [int] 12, but got [int] 0.
   at $servers.Count | Should-Be 12, C:\Users\labadmin\pslab\demo\Discovery.Tests.ps1:6

Running tests from 'C:\Users\labadmin\pslab\demo\DiscoveryFixed.Tests.ps1'
Describing Get-OpsServer (fixed setup)
  [+] returns 12 servers 5ms
Tests completed in 1.19s
Tests Passed: 1, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0

如何验证:两个文件唯一的区别是把两行初始化代码包进了 BeforeAll { }。在有缺陷的文件中,$servers 在运行阶段为 $null,而 $null.Count 是 0。常见错误:把变量改成 $global: 来“修复” —— 这会掩盖缺陷并把状态泄漏到其他文件。生产用法:代码评审规则“BeforeAll/BeforeDiscovery/It 之外不允许有可执行代码”。

2. Should-* 与 Should -Be(故意失败 3 个)

Describe 'Should-* vs Should -Be' {
    It 'classic: string "1" equals int 1' {
        '1' | Should -Be 1
    }
    It 'new: Expected drives the type, so "1" also equals 1' {
        '1' | Should-Be 1
    }
    It 'classic -Be is case-insensitive' {
        'PROD' | Should -Be 'prod'
    }
    It 'Should-BeString -CaseSensitive (fails on purpose)' {
        'PROD' | Should-BeString 'prod' -CaseSensitive
    }
    It 'piping @() into a value assertion (fails on purpose)' {
        @() | Should-Be 0
    }
    It 'collection order matters (fails on purpose)' {
        'web', 'api' | Should-BeCollection @('api', 'web')
    }
    It 'Should-BeEquivalent shows the property that differs (fails on purpose)' {
        [pscustomobject]@{ Name = 'web-01'; Env = 'prod'; Port = 8080 } |
            Should-BeEquivalent ([pscustomobject]@{ Name = 'web-01'; Env = 'dev'; Port = 8080 })
    }
}
Pester v6.2.0

Running tests from 1 files.

Running tests from 'C:\Users\labadmin\pslab\demo\Assertions.Tests.ps1'
Describing Should-* vs Should -Be
  [+] classic: string "1" equals int 1 127ms
  [+] new: Expected drives the type, so "1" also equals 1 106ms
  [+] classic -Be is case-insensitive 20ms
  [-] Should-BeString -CaseSensitive (fails on purpose) 151ms
   Expected strings to be the same, but they were different.
   String lengths are both 4.
   Strings differ at index 0.
   Expected: 'prod'
   But was:  'PROD'
              ^
   at 'PROD' | Should-BeString 'prod' -CaseSensitive, C:\Users\labadmin\pslab\demo\Assertions.Tests.ps1:12
  [-] piping @() into a value assertion (fails on purpose) 37ms
   Expected [int] 0, but got [null] $null.
   at @() | Should-Be 0, C:\Users\labadmin\pslab\demo\Assertions.Tests.ps1:15
  [+] collection order matters (fails on purpose) 36ms
  [-] Should-BeEquivalent shows the property that differs (fails on purpose) 167ms
   Expected and actual are not equivalent!
   Expected:
   PSObject{
       Env='dev';
       Name='web-01';
       Port=8080;
   }
   Actual:
   PSObject{
       Env='prod';
       Name='web-01';
       Port=8080;
   }
   Summary:
   Expected property .Env with value 'dev' to be equivalent to the actual value, but got 'prod'.
   at Should-BeEquivalent ([pscustomobject]@{ Name = 'web-01'; Env = 'dev'; Port = 8080 }), C:\Users\labadmin\pslab\demo\Assertions.Tests.ps1:22
   at <ScriptBlock>, C:\Users\labadmin\pslab\demo\Assertions.Tests.ps1:21
Tests completed in 1.62s
Tests Passed: 4, Failed: 3, Skipped: 0, Inconclusive: 0, NotRun: 0

如何验证:两种语法都接受 '1' 等于 1(由期望值的类型驱动转换)。Should-BeString -CaseSensitive 显示了差异位置和插入符。@() | Should-Be 0 以 $null 失败 —— 管道会展开空数组;请用 Should-Be -Actual @() -Expected … 或集合断言。“collection order matters” 这个测试通过了,这正是下面要解释的意外。

3. Should-BeCollection 忽略顺序

Describe 'Should-BeCollection and order' {
    It 'different order' { 'web', 'api' | Should-BeCollection @('api', 'web') }
    It 'different items (fails on purpose)' { 'web', 'api' | Should-BeCollection @('api', 'db') }
    It 'order checked with -join (fails on purpose)' { ('web', 'api') -join ',' | Should-Be 'api,web' }
}
Pester v6.2.0

Running tests from 1 files.

Running tests from 'C:\Users\labadmin\pslab\demo\Order.Tests.ps1'
Describing Should-BeCollection and order
  [+] different order 117ms
  [-] different items (fails on purpose) 189ms
   Expected [Object[]] @('api', 'db') to be present in [Object[]] @('web', 'api') in any order, but some values were not.
   Missing in actual: ''db' (index 1)'
   Extra in actual: ''web' (index 0)'
   at It 'different items (fails on purpose)' { 'web', 'api' | Should-BeCollection @('api', 'db') }, C:\Users\labadmin\pslab\demo\Order.Tests.ps1:3
  [-] order checked with -join (fails on purpose) 36ms
   Expected [string] 'api,web', but got [string] 'web,api'.
   at It 'order checked with -join (fails on purpose)' { ('web', 'api') -join ',' | Should-Be 'api,web' }, C:\Users\labadmin\pslab\demo\Order.Tests.ps1:4
Tests completed in 1.35s
Tests Passed: 1, Failed: 2, Skipped: 0, Inconclusive: 0, NotRun: 0

4. Pester 6 的严格性:空 -ForEach、带过滤器的 Mock、DisableV5

BeforeAll { function Get-Thing ($Name) { "real $Name" } }
Describe 'Pester 6 behaviors' {
    It 'filtered mock, non-matching call' {
        Mock Get-Thing -ParameterFilter { $Name -eq 'a' } { 'mocked a' }
        Get-Thing -Name a | Should-Be 'mocked a'
        Get-Thing -Name b | Should-Be 'real b'
    }
    It 'empty ForEach' -ForEach @() { 1 | Should-Be 1 }
}
Import-Module Pester -MinimumVersion 6.0.0
Invoke-Pester -Path ./demo/V6.Tests.ps1 -Output Detailed
$c = New-PesterConfiguration
$c.Run.Path = './demo/DisableV5.Tests.ps1'
$c.Should.DisableV5 = $true
$c.Output.Verbosity = 'Detailed'
Invoke-Pester -Configuration $c
Pester v6.2.0

Running tests from 1 files.
[-] Discovery in C:\Users\labadmin\pslab\demo\V6.Tests.ps1 failed with:
System.ArgumentException: Value can not be null or empty array. If this is expected, use -AllowNullOrEmptyForEach on this It, or set the Run.FailOnNullOrEmptyForEach configuration option to $false to allow it for the whole run. (Parameter 'ForEach')
at It, C:\Users\labadmin\pslab\modules\Pester\6.2.0\Pester.psm1: line 17117
at <ScriptBlock>, C:\Users\labadmin\pslab\demo\V6.Tests.ps1: line 8
at New-Block, C:\Users\labadmin\pslab\modules\Pester\6.2.0\Pester.psm1: line 790
at Describe, C:\Users\labadmin\pslab\modules\Pester\6.2.0\Pester.psm1: line 16285
at <ScriptBlock>, C:\Users\labadmin\pslab\demo\V6.Tests.ps1: line 2
at <ScriptBlock>, C:\Users\labadmin\pslab\modules\Pester\6.2.0\Pester.psm1: line 3412
at Invoke-File, C:\Users\labadmin\pslab\modules\Pester\6.2.0\Pester.psm1: line 3421
at Invoke-BlockContainer, C:\Users\labadmin\pslab\modules\Pester\6.2.0\Pester.psm1: line 3336
at Invoke-ContainerDiscovery, C:\Users\labadmin\pslab\modules\Pester\6.2.0\Pester.psm1: line 1544
at Invoke-Test, C:\Users\labadmin\pslab\modules\Pester\6.2.0\Pester.psm1: line 2745
at Invoke-Pester<End>, C:\Users\labadmin\pslab\modules\Pester\6.2.0\Pester.psm1: line 5632
at <ScriptBlock>, C:\Users\labadmin\pslab\lab\p7.ps1: line 2

Running tests from 'C:\Users\labadmin\pslab\demo\V6.Tests.ps1'
Describing Pester 6 behaviors
  [-] filtered mock, non-matching call 652ms
   RuntimeException: No mock for command 'Get-Thing' matched the call: none of the parameter filters matched, and there is no default mock to fall back to. Add a default mock (e.g. `Mock Get-Thing { ... }`) or adjust an existing -ParameterFilter.
   The following parameter filters were evaluated and did not match:
       { $Name -eq 'a' }  bound parameters: Name = b
   at <ScriptBlock><End>, <No file>:86
   at <ScriptBlock>, C:\Users\labadmin\pslab\demo\V6.Tests.ps1:6
[-] C:\Users\labadmin\pslab\demo\V6.Tests.ps1 failed with:
ArgumentException: Value can not be null or empty array. If this is expected, use -AllowNullOrEmptyForEach on this It, or set the Run.FailOnNullOrEmptyForEach configuration option to $false to allow it for the whole run. (Parameter 'ForEach')
at <ScriptBlock>, C:\Users\labadmin\pslab\demo\V6.Tests.ps1:8
Tests completed in 1.73s
Tests Passed: 0, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0
Container failed: 1
  - C:\Users\labadmin\pslab\demo\V6.Tests.ps1
Pester v6.2.0

Running tests from 1 files.

Running tests from 'C:\Users\labadmin\pslab\demo\DisableV5.Tests.ps1'
Describing DisableV5
  [-] classic Should 44ms
   RuntimeException: Pester Should -Be syntax is disabled. Use Should-Be (without space), or enable it by setting: $PesterPreference.Should.DisableV5 = $false
   at <ScriptBlock>, C:\Users\labadmin\pslab\demo\DisableV5.Tests.ps1:1
Tests completed in 181ms
Tests Passed: 0, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0

一次运行中展示了 Pester 6 的三种行为:空 -ForEach 让文件在发现阶段失败;只有 -ParameterFilter 且不匹配的 Mock 会抛错,而不是调用真实命令(模块 4);Should.DisableV5 让 Should -Be 变成错误。

5. 第一批真正的 OpsKit 测试:带 TestDrive 和 -ForEach 的 Get-OpsServer

BeforeAll {
    Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force
    $csv = Join-Path $TestDrive 'servers.csv'
    @'
Name,Env,Region,IP,Role,Monitored
web-01,dev,canadacentral,10.10.1.21,web,true
db-01,dev,canadacentral,10.10.1.23,db,false
web-01,prod,canadacentral,10.30.1.41,web,true
edge-01,prod,ca-central-1,10.30.2.51,"web,api",true
db-01,prod,canadacentral,10.30.1.44,db,false
'@ | Set-Content -LiteralPath $csv
}

Describe 'Get-OpsServer' {
    Context 'without filters' {
        BeforeAll {
            $servers = @(Get-OpsServer -Path $csv)
        }
        It 'returns one object per CSV row' {
            $servers.Count | Should-Be 5
        }
        It 'converts Monitored to a real boolean' {
            $servers[1].Monitored | Should-BeFalse
            Should-HaveType -Actual $servers[0].Monitored -Expected ([bool])
        }
        It 'splits a quoted multi-role value into an array' {
            $edge = $servers | Where-Object Name -eq 'edge-01'
            $edge.Role | Should-BeCollection @('web', 'api')
        }
        It 'still supports the classic Should syntax' {
            $servers[0].Name | Should -Be 'web-01'
        }
    }

    Context 'with filters' {
        It 'filters by environment <Env>: <Count> servers' -ForEach @(
            @{ Env = 'dev'; Count = 2 }
            @{ Env = 'prod'; Count = 3 }
        ) {
            @(Get-OpsServer -Path $csv -Environment $Env).Count | Should-Be $Count
        }
        It 'filters by role, including multi-role servers' {
            (Get-OpsServer -Path $csv -Environment prod -Role api).Name | Should-Be 'edge-01'
        }
        It 'returns only monitored servers with -MonitoredOnly' {
            Get-OpsServer -Path $csv -MonitoredOnly | Should-All { $_.Monitored -eq $true }
        }
        It 'rejects an unknown environment' {
            { Get-OpsServer -Path $csv -Environment qa } | Should-Throw -ExceptionType ([System.Management.Automation.ParameterBindingException])
        }
    }
}
Running tests from 'C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsServer.Tests.ps1'
Describing Get-OpsServer
 Context without filters
   [+] returns one object per CSV row 22ms
   [+] converts Monitored to a real boolean 40ms
   [+] splits a quoted multi-role value into an array 29ms
   [+] still supports the classic Should syntax 69ms
 Context with filters
   [+] filters by environment dev: 2 servers 70ms
   [+] filters by environment prod: 3 servers 4ms
   [+] filters by role, including multi-role servers 14ms
   [+] returns only monitored servers with -MonitoredOnly 37ms
   [+] rejects an unknown environment 27ms

如何验证:测试用的 CSV 在文件级 BeforeAll 中写入 $TestDrive,因此测试从不依赖 ~/pslab/data,在 CI 中表现一致。-ForEach 测试被展开成两个带名称的测试。Should-All 遇到空集合会失败 —— 这一特性在模块 8 中抓住了一个真实缺陷。

目标:为 Get-OpsConfig 和 Invoke-OpsBackup 编写只使用 TestDrive 的测试。环境:Pester 6.2.0、OpsKit v0.5。费用:无。

Get-OpsConfig —— 测试配置文件、用 Should-BeEquivalent 深度比较,以及三条错误路径:
BeforeAll {
    Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force
    $configPath = Join-Path $TestDrive 'opskit.config.psd1'
    @'
@{
    DefaultEnv   = 'dev'
    Environments = @{
        dev  = @{ Region = 'canadacentral'; HealthUrl = 'http://10.10.1.21:8080/healthz' }
        prod = @{ Region = 'canadacentral'; HealthUrl = 'https://shop.example.com/healthz'; RequireConfirm = $true }
    }
    Health       = @{ TimeoutSec = 5 }
}
'@ | Set-Content -LiteralPath $configPath
}

Describe 'Get-OpsConfig' {
    It 'returns the whole configuration as a hashtable' {
        $config = Get-OpsConfig -Path $configPath
        $config | Should-BeHashtable
        $config.DefaultEnv | Should-Be 'dev'
    }
    It 'returns one environment as an object' {
        Get-OpsConfig -Path $configPath -Environment prod | Should-BeEquivalent ([pscustomobject]@{
                Name           = 'prod'
                Region         = 'canadacentral'
                HealthUrl      = 'https://shop.example.com/healthz'
                RequireConfirm = $true
            })
    }
    It 'defaults RequireConfirm to $false' {
        (Get-OpsConfig -Path $configPath -Environment dev).RequireConfirm | Should-BeFalse
    }
    It 'names the known environments when the environment is unknown' {
        { Get-OpsConfig -Path $configPath -Environment qa } |
            Should-Throw -ExceptionMessage "Unknown environment 'qa'. Known environments: dev, prod"
    }
    It 'throws FileNotFoundException for a missing file' {
        { Get-OpsConfig -Path (Join-Path $TestDrive 'nope.psd1') } |
            Should-Throw -ExceptionType ([System.IO.FileNotFoundException])
    }
    It 'rejects a file without the required keys' {
        $bad = Join-Path $TestDrive 'bad.psd1'
        Set-Content -LiteralPath $bad -Value "@{ DefaultEnv = 'dev' }"
        { Get-OpsConfig -Path $bad } | Should-Throw -ExceptionMessage "*missing the 'Environments' key*"
    }
}
Invoke-OpsBackup —— 每个测试使用全新的源目录和目标目录(BeforeEach)、古怪的文件名、由 -ForEach 驱动的轮换测试,并 Mock Get-Date 以得到稳定的文件名(Mock 在模块 4 讲解):
BeforeAll {
    Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force
}

Describe 'Invoke-OpsBackup' {
    BeforeEach {
        # A fresh source and destination for every test (TestDrive is shared inside one Describe).
        $source = Join-Path $TestDrive "src-$([guid]::NewGuid())"
        $destination = Join-Path $TestDrive "dst-$([guid]::NewGuid())"
        $null = New-Item -ItemType Directory -Path (Join-Path $source 'sub dir') -Force
        Set-Content -LiteralPath (Join-Path $source 'report 2026.txt') -Value 'r'
        Set-Content -LiteralPath (Join-Path $source '[draft] notes.md') -Value 'd'
        Set-Content -LiteralPath (Join-Path $source 'sub dir/nested file.log') -Value 'n'
        Set-Content -LiteralPath (Join-Path $source 'scratch.tmp') -Value 't'
        Mock Get-Date -ModuleName OpsKit { '20261124-101500' }
    }

    It 'creates one zip named after the timestamp' {
        $zip = Invoke-OpsBackup -Source $source -Destination $destination
        $zip.Name | Should-Be 'backup-20261124-101500.zip'
    }
    It 'keeps relative paths, odd names included, and skips excluded files' {
        $zip = Invoke-OpsBackup -Source $source -Destination $destination
        $archive = [System.IO.Compression.ZipFile]::OpenRead($zip.FullName)
        try { $entries = $archive.Entries.FullName | Sort-Object } finally { $archive.Dispose() }
        $entries | Should-BeCollection @('[draft] notes.md', 'report 2026.txt', 'sub dir/nested file.log')
    }
    It 'changes nothing with -WhatIf' {
        Invoke-OpsBackup -Source $source -Destination $destination -WhatIf
        Test-Path -LiteralPath $destination | Should-BeFalse
    }
    It 'keeps only the newest <Keep> backups' -ForEach @(@{ Keep = 2 }, @{ Keep = 3 }) {
        $null = New-Item -ItemType Directory -Path $destination
        'backup-20261120-010000.zip', 'backup-20261121-010000.zip', 'backup-20261122-010000.zip' |
            ForEach-Object { Set-Content -LiteralPath (Join-Path $destination $_) -Value 'old' }
        $null = Invoke-OpsBackup -Source $source -Destination $destination -Keep $Keep
        $left = (Get-ChildItem -LiteralPath $destination -Filter 'backup-*.zip').Name | Sort-Object -Descending
        $left.Count | Should-Be $Keep
        $left[0] | Should-Be 'backup-20261124-101500.zip'
    }
    It 'asks ShouldProcess before removing an expired backup' {
        $null = New-Item -ItemType Directory -Path $destination
        Set-Content -LiteralPath (Join-Path $destination 'backup-20261101-010000.zip') -Value 'old'
        Mock Remove-Item -ModuleName OpsKit { }
        $null = Invoke-OpsBackup -Source $source -Destination $destination -Keep 1
        Should-Invoke Remove-Item -ModuleName OpsKit -Times 1 -Exactly -ParameterFilter {
            $LiteralPath -like '*backup-20261101-010000.zip'
        }
    }
    It 'fails clearly when the source folder does not exist' {
        { Invoke-OpsBackup -Source (Join-Path $TestDrive 'missing') -Destination $destination } |
            Should-Throw -ExceptionMessage 'Invoke-OpsBackup: source folder not found:*'
    }
}
运行:
Invoke-Pester -Path ./OpsKit/tests/Get-OpsConfig.Tests.ps1, ./OpsKit/tests/Invoke-OpsBackup.Tests.ps1 -Output Detailed
Describing Get-OpsConfig
  [+] returns the whole configuration as a hashtable 127ms
  [+] returns one environment as an object 160ms
  [+] defaults RequireConfirm to $false 20ms
  [+] names the known environments when the environment is unknown 58ms
  [+] throws FileNotFoundException for a missing file 29ms
  [+] rejects a file without the required keys 25ms
Describing Invoke-OpsBackup
  [+] creates one zip named after the timestamp 150ms
  [+] keeps relative paths, odd names included, and skips excluded files 53ms
What if: Performing the operation "Create backup of 3 file(s) from C:\Users\labadmin\AppData\Local\Temp\Pester_c4dd\src-1319…" on target "…\backup-20261124-101500.zip".
  [+] changes nothing with -WhatIf 39ms
  [+] keeps only the newest 2 backups 86ms
  [+] keeps only the newest 3 backups 46ms
  [+] asks ShouldProcess before removing an expired backup 132ms
  [+] fails clearly when the source folder does not exist 42ms

“What if:” 这一行是测试期间宿主打印的真实 -WhatIf 消息 —— 无害,而且证明确实调用了 ShouldProcess。

故意破坏:把 Invoke-OpsBackup.ps1 中的 'backup-{0}.zip' 改成 'bak-{0}.zip',重新运行,读一读哪些测试失败以及原因,然后改回。
清理:无需清理 —— TestDrive 目录由 Pester 删除。

案例 1:测试全绿,模块却是坏的

问题:一个测试套件连续几个月都通过,而某个函数早已损坏。根因:文件在顶层导入模块,并在 Describe 块体中给 $expected 赋值;运行阶段 $expected 为 $null,断言 $result | Should -Be $expected 比较的是 $null 与 $null。修复:把初始化移到 BeforeAll;对测试依赖的值加 Should-NotBeNull 保护。

案例 2:构建服务器运行的是 Pester 3.4

问题:一台 Windows 构建代理打印 “The BeforeAll command may only be used inside a Describe block.”。根因:镜像中只有系统自带的 Pester。修复:在流水线中安装固定版本,并用 -MinimumVersion 6.0.0 导入,让错误版本明确地失败。

案例 3:单独运行通过、一起运行失败的测试

问题:备份测试只在其他测试之后运行时失败。根因:它们共用 $TestDrive 中的一个固定路径,而前一个测试留下了 zip 文件(TestDrive 按块而不是按测试划分)。修复:在 BeforeEach 中创建唯一的子目录 —— OpsKit 的备份测试正是这样做的。

常见错误与修复

The BeforeAll command may only be used inside a Describe block.

原因:加载的是 Pester 3/4。修复:Get-Module Pester;Remove-Module Pester; Import-Module Pester -MinimumVersion 6.0.0。

Expected [int] 12, but got [int] 0 / It 中的变量为 $null

原因:变量是在发现阶段赋值的。修复:把它移到 BeforeAll 或 BeforeEach 中。

Value can not be null or empty array … use -AllowNullOrEmptyForEach

原因:Pester 6 拒绝空的 -ForEach(通常是发现阶段计算的数据结果为空)。修复:在 BeforeDiscovery 中正确计算数据;如果为空是合理的,加 -AllowNullOrEmptyForEach。

Pester Should -Be syntax is disabled. Use Should-Be (without space)

原因:配置(或 $PesterPreference)中设置了 Should.DisableV5 = $true。修复:迁移该断言,或把它改回 $false。

Set-ItResult: A parameter cannot be found that matches parameter name 'Pending'.

原因:Pester 6 移除了 Pending 状态。修复:使用 Set-ItResult -Skipped -Because '…' 或 -Inconclusive。

命令行练习
1. 编写一个数据驱动测试,检查 ~/pslab/data/servers.csv 中每个环境的服务器数量(dev 3、staging 3、prod 6)。
BeforeAll { Import-Module ~/pslab/OpsKit/OpsKit.psd1 -Force }
Describe 'dataset' {
    It '<Env> has <Count> servers' -ForEach @(
        @{ Env = 'dev'; Count = 3 }, @{ Env = 'staging'; Count = 3 }, @{ Env = 'prod'; Count = 6 }
    ) {
        @(Get-OpsServer -Path ~/pslab/data/servers.csv -Environment $Env).Count | Should-Be $Count
    }
}
2. 只运行名称中包含 “WhatIf” 的测试,并输出详细信息。
Invoke-Pester -Path ./OpsKit/tests -FullNameFilter '*WhatIf*' -Output Detailed
场景分析
同事的测试文件在顶部从 CSV 加载 5,000 行来构造 -ForEach 用例,结果即使你只过滤出一个无关的测试,整个套件也变慢了。为什么?怎么改?

顶层代码和 BeforeDiscovery 在每次运行该文件的发现阶段都会执行,即使过滤器最终排除了它的所有测试 —— 构建测试树需要这些数据。可选方案:用少量有代表性的用例(边界值、异常值)代替每一行;把批量校验移到一个在运行阶段循环的 It 中;或者给该文件打标签,在本地快速运行时排除它。让发现阶段保持轻量。

已验证的教学视频

▶
PowerShell 7 Tutorials for Intermediates #5 : Pester (Testing) — JackedProgrammer
英文 · 使用 Pester 5 语法的 Describe / It / Should
▶
Unit Testing with Pester Framework | PowerShell Testing Tutorial for Beginners — CodeLucky
英文 · 第一个单元测试

两个视频都早于 Pester 6:使用的是仍然可用的 Should -Be。没有找到讲解 Pester 6 Should-* 系列的已验证视频;请参考 Pester 6.0.0 发布说明和本模块。

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–25 秒
画面:一个测试文件;黄色扫描线(发现)掠过,点亮 Describe/Context 块体,并把 It 方框登记下来但不打开。
旁白:Pester 会读你的文件两遍。
镜头 2 · 25–55 秒
画面:绿色扫描线(运行)打开 BeforeAll,再打开每个 It;黄色那一遍留下的变量逐渐淡出。
旁白:初始化属于 BeforeAll —— 其他地方的东西到测试运行时已经不在了。
镜头 3 · 55–75 秒
画面:Should-Be、Should-BeString、Should-BeEquivalent 卡片及其失败消息。
旁白:Pester 6 的断言有类型意识,失败原因说得清清楚楚。
镜头 4 · 75–90 秒
画面:一个 TestDrive 目录随 Describe 块出现又消失。
旁白:测试写的每个文件都放进 TestDrive。
或测验得分 ≥ 70%

模块 4 · Mock 与测试设计:Mock、Should -Invoke、InModuleScope

21:00 – 28:00 · 单元测试不能调用真实的 Web 服务器、时钟或云。Mock 在测试期间替换一个命令,记录每次调用,并让你断言代码是如何使用它的 —— 前提是 Mock 放在了正确的作用域里
7 分钟Mock · Should-Invoke · InModuleScope★★★★★
学习目标
  • 用替换脚本块 Mock 一个命令,用 -ParameterFilter 做条件 Mock,并且知道在 Pester 6 中,不匹配任何过滤器且没有默认 Mock 的调用会抛错。
  • 用 -ModuleName OpsKit 让 Mock 作用于模块内部发出的调用,用 InModuleScope 调用私有函数。
  • 用 Should-Invoke / Should-NotInvoke(或经典 Should -Invoke)配合 -Times、-Exactly 和过滤器断言调用,并读懂失败时 Pester 打印的调用历史。
  • 测试 -WhatIf、错误路径(Should-Throw)、重试(Mock Invoke-RestMethod + Start-Sleep)、原生命令(git)以及未安装的命令(Get-AzResource)。
前置条件:模块 3、第 4 课(模块作用域)、第 7 课(Invoke-OpsApi)。重要度:★★★★★

是什么:Mock 是一个在命令查找中胜出的函数

Mock Invoke-WebRequest { … } 为当前块定义一个类似函数的替身,参数与真实命令相同。因为在命令优先级中函数先于 cmdlet(第 1 课),所以在同一作用域中调用 Invoke-WebRequest 的代码会得到 Mock。Pester 会记录每次调用及其绑定的参数。

为什么:快速、确定、离线

依赖在单元测试中的问题Mock 成
Invoke-WebRequest、Invoke-RestMethod依赖网络、慢、不稳定、有真实副作用返回 [pscustomobject]@{ StatusCode = 503 } 或抛出 HttpResponseException
Get-Date每次运行都不同{ '20261124-101500' }
Start-Sleep重试退避让测试变慢{ } 并统计调用次数
Remove-Item、Restart-Service破坏性操作{ } + 带过滤器的 Should-Invoke
git、az、kubectlCI 中未安装原生工具或需要凭据Mock git { 'main' }(对应用程序同样有效)
Get-AzResource运行器上没有安装该模块先定义一个桩函数,再 Mock 它(Mock 要求命令存在)

怎么做:作用域决定 Mock 是否可见

你的代码在何处调用依赖……Mock 写法
点源进测试的函数(脚本,而非模块)Mock X { }
模块 OpsKit 内部(公有或私有函数)Mock X -ModuleName OpsKit { } —— 以及 Should-Invoke X -ModuleName OpsKit
想直接调用私有函数InModuleScope OpsKit -Parameters @{ … } { Resolve-OpsPath … }

优先通过公共接口配合 -ModuleName 测试;谨慎使用 InModuleScope(它会让测试与内部实现耦合),并用 -Parameters 传值,而不是依赖外部变量。

何时用:过滤器、默认 Mock 与验证

同一命令可以有多个 Mock:最近定义且 -ParameterFilter 匹配的 Mock 胜出;没有过滤器的 Mock 是默认 Mock。在 Pester 6 中,如果没有过滤器匹配又没有默认 Mock,调用会抛错 “No mock for command … matched the call”,而不是悄悄调用真实命令(已验证)—— 所以先定义默认 Mock。用 Should-Invoke -Times N -Exactly 验证;不加 -Exactly 时 -Times 表示“至少”。Should-Invoke 失败时会打印每次记录的调用,匹配过滤器的用 [*] 标记。

常见误区① “Mock Invoke-WebRequest 会在任何地方生效” —— 不带 -ModuleName 时在模块内部无效(已复现:真实请求被发出,返回状态 0)。② “过滤器不匹配时会回落到真实命令” —— Pester 6 已移除;会抛错。③ “-ParameterFilter { $TimeoutSec -eq 2 } 会失败,因为真实参数名是 -ConnectionTimeoutSeconds” —— Pester 6 在过滤器中也匹配参数别名(已验证:记录的调用显示 -ConnectionTimeoutSeconds 5,基于 $TimeoutSec 的过滤器依然生效)。④ “测试 -WhatIf 需要 Mock” —— 检查什么都没改变即可;只对破坏性命令用 Mock 加 Should-Invoke。⑤ “Mock 会泄漏到下一个测试” —— 在 It 或 BeforeEach 中定义的 Mock 在测试结束后移除;BeforeAll 中的 Mock 在整个块内有效。

图解:哪个调用方能看到哪个 Mock

测试作用域(Pester 容器) Mock Invoke-WebRequest { 200 }只对从本作用域发出的调用可见 Test-OpsEndpoint -Uri …导出函数:函数体在 OpsKit 的作用域中运行 InModuleScope OpsKit { Resolve-OpsPath '~' }在模块内部运行该块:私有函数可见 模块作用域:OpsKit Mock Invoke-WebRequest -ModuleName OpsKit { 200 }注入到这里:OpsKit 内部的调用得到它 Test-OpsEndpoint 函数体Invoke-WebRequest -Uri $Uri -TimeoutSec … 私有:Resolve-OpsPath、Write-OpsLog未导出 → 测试无法直接调用
图 4-1:对 Invoke-WebRequest 的调用发生在 OpsKit 的作用域中,所以只有用 -ModuleName OpsKit 注入的 Mock 才能替换它

Mock 解析器:这次调用会落到哪里?

每个场景跟踪一次调用,从被测代码一直到最终响应它的对象。

就绪。
动画背后的真实机制 Mock 用原命令的参数元数据生成一个代理函数,并定义在目标会话状态中(测试作用域,或使用 -ModuleName 时的模块作用域)。代理按从新到旧的顺序评估已注册的行为:第一个 -ParameterFilter 返回 true 的行为执行;否则执行默认行为;否则在 Pester 6 中报错。每次调用都追加到历史记录中,Should-Invoke 随后对其过滤和计数。

命令表

命令用途说明
Mock Cmd { … }默认替换在 BeforeAll/BeforeEach/It 中定义
Mock Cmd -ParameterFilter { $Name -eq 'x' } { … }条件替换变量就是命令的参数(别名也可用)
Mock Cmd -ModuleName OpsKit { … }Mock 模块内部发出的调用Should-Invoke 也要用相同的 -ModuleName
Should-Invoke Cmd -Times 2 -Exactly -ModuleName OpsKit断言调用次数经典写法:Should -Invoke Cmd -Times 2 -Exactly
Should-NotInvoke Cmd -ModuleName OpsKit断言没有调用非常适合 -WhatIf 测试
InModuleScope OpsKit -Parameters @{ P = 1 } { … }在模块内部运行代码私有函数和 $script: 变量
New-MockObject -Type System.Diagnostics.Process某个类型的假 .NET 对象用于强类型参数
{ … } | Should-Throw -ExceptionMessage '*404*' -ExceptionType ([…])错误路径把调用包在脚本块中

1. Mock 作用域、原生命令与调用历史

BeforeAll {
    Import-Module "$PSScriptRoot/../OpsKit/OpsKit.psd1" -Force
    function Get-RepoBranch { (git rev-parse --abbrev-ref HEAD).Trim() }
}

Describe 'Mock scope' {
    It 'a mock WITHOUT -ModuleName does not reach code inside the module (fails on purpose)' {
        Mock Invoke-WebRequest { [pscustomobject]@{ StatusCode = 200 } }
        (Test-OpsEndpoint -Uri 'https://nowhere.invalid/' -TimeoutSec 1).StatusCode | Should-Be 200
    }
    It 'a mock WITH -ModuleName OpsKit does' {
        Mock Invoke-WebRequest -ModuleName OpsKit { [pscustomobject]@{ StatusCode = 200 } }
        (Test-OpsEndpoint -Uri 'https://nowhere.invalid/').StatusCode | Should-Be 200
    }
}

Describe 'Mocking a native command' {
    It 'replaces git with a function for the duration of the test' {
        Mock git { 'feature/opskit-1.0' }
        Get-RepoBranch | Should-Be 'feature/opskit-1.0'
        Should -Invoke git -Times 1 -Exactly -ParameterFilter { $args -contains '--abbrev-ref' }
    }
}

Describe 'Invocation history' {
    It 'shows every recorded call when Should-Invoke fails (fails on purpose)' {
        Mock Invoke-WebRequest -ModuleName OpsKit { [pscustomobject]@{ StatusCode = 200 } }
        $null = 'https://a.example.com/', 'https://b.example.com/' | Test-OpsEndpoint
        Should-Invoke Invoke-WebRequest -ModuleName OpsKit -Times 2 -Exactly -ParameterFilter { $Uri.Host -eq 'a.example.com' }
    }
}
Pester v6.2.0

Running tests from 1 files.

Running tests from 'C:\Users\labadmin\pslab\demo\Mocking.Tests.ps1'
Describing Mock scope
  [-] a mock WITHOUT -ModuleName does not reach code inside the module (fails on purpose) 484ms
   Expected [int] 200, but got [int] 0.
   at (Test-OpsEndpoint -Uri 'https://nowhere.invalid/' -TimeoutSec 1).StatusCode | Should-Be 200, C:\Users\labadmin\pslab\demo\Mocking.Tests.ps1:9
  [+] a mock WITH -ModuleName OpsKit does 147ms

Describing Mocking a native command
  [+] replaces git with a function for the duration of the test 164ms

Describing Invocation history
  [-] shows every recorded call when Should-Invoke fails (fails on purpose) 178ms
   Expected Invoke-WebRequest in module OpsKit to be called 2 times exactly, but was called 1 time
   Performed invocations:
     [*] Invoke-WebRequest -ConnectionTimeoutSeconds 5 -Uri uri{AbsolutePath='/'; AbsoluteUri='https://a.example.com/'; Authority='a.example.com'; DnsSafeHost='a.example.com'; Fragment=<empty>; Host='a.example.com'; HostNameType=Dns; IdnHost='a.example.com'; IsAbsoluteUri=$true; IsDefaultPort=$true; IsFile=$false; IsLoopback=$false; IsUnc=$false; LocalPath='/'; OriginalString='https://a.example.com/'; PathAndQuery='/'; Port=443; Query=<empty>; Scheme='https'; Segments=@('/'); UserEscaped=$false; UserInfo=<empty>} -ErrorAction Stop -SkipHttpErrorCheck True from C:\Users\labadmin\pslab\demo\Mocking.Tests.ps1:27
     [ ] Invoke-WebRequest -ConnectionTimeoutSeconds 5 -Uri uri{AbsolutePath='/'; AbsoluteUri='https://b.example.com/'; Authority='b.example.com'; DnsSafeHost='b.example.com'; Fragment=<empty>; Host='b.example.com'; HostNameType=Dns; IdnHost='b.example.com'; IsAbsoluteUri=$true; IsDefaultPort=$true; IsFile=$false; IsLoopback=$false; IsUnc=$false; LocalPath='/'; OriginalString='https://b.example.com/'; PathAndQuery='/'; Port=443; Query=<empty>; Scheme='https'; Segments=@('/'); UserEscaped=$false; UserInfo=<empty>} -ErrorAction Stop -SkipHttpErrorCheck True from C:\Users\labadmin\pslab\demo\Mocking.Tests.ps1:27
   at Should-Invoke Invoke-WebRequest -ModuleName OpsKit -Times 2 -Exactly -ParameterFilter { $Uri.Host -eq 'a.example.com' }, C:\Users\labadmin\pslab\demo\Mocking.Tests.ps1:29
Tests completed in 1.85s
Tests Passed: 2, Failed: 2, Skipped: 0, Inconclusive: 0, NotRun: 0

如何验证:测试 1 真的请求了 https://nowhere.invalid/(Mock 放错了作用域),Test-OpsEndpoint 返回状态 0。测试 3 替换了 git —— 一个原生应用程序 —— 经典 Should -Invoke 通过 $args 检查了它的参数。测试 4 的失败信息列出了两次记录的调用,匹配 a.example.com 的那次标为 [*];注意 [uri] 参数被展开显示,而真实参数名是 -ConnectionTimeoutSeconds。

2. Test-OpsEndpoint:默认 Mock + 带过滤器的 Mock

function Test-OpsEndpoint {
    <#
    .SYNOPSIS
        Calls an HTTP health endpoint and returns one result object per URI.
    .EXAMPLE
        Get-OpsConfig -Environment dev | Test-OpsEndpoint
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [Alias('HealthUrl')]
        [uri]$Uri,

        [ValidateRange(1, 60)]
        [int]$TimeoutSec = 5
    )
    process {
        $timer = [System.Diagnostics.Stopwatch]::StartNew()
        try {
            $response = Invoke-WebRequest -Uri $Uri -TimeoutSec $TimeoutSec -SkipHttpErrorCheck -ErrorAction Stop
            $status = [int]$response.StatusCode
            $problem = $null
        } catch {
            $status = 0
            $problem = $_.Exception.Message
        }
        [pscustomobject]@{
            PSTypeName = 'OpsKit.EndpointResult'
            Uri        = $Uri.AbsoluteUri
            StatusCode = $status
            Healthy    = $status -ge 200 -and $status -le 299
            Ms         = $timer.ElapsedMilliseconds
            Error      = $problem
        }
    }
}
BeforeAll {
    Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force
}

Describe 'Test-OpsEndpoint' {
    BeforeEach {
        # Default mock: every URL answers 200. Specific mocks below override it.
        Mock Invoke-WebRequest -ModuleName OpsKit { [pscustomobject]@{ StatusCode = 200 } }
        Mock Invoke-WebRequest -ModuleName OpsKit -ParameterFilter { $Uri.Host -eq 'down.example.com' } {
            [pscustomobject]@{ StatusCode = 503 }
        }
        Mock Invoke-WebRequest -ModuleName OpsKit -ParameterFilter { $Uri.Host -eq 'nowhere.invalid' } {
            throw [System.Net.Http.HttpRequestException]::new('No such host is known.')
        }
    }

    It 'reports a 200 as healthy' {
        $r = Test-OpsEndpoint -Uri 'https://shop.example.com/healthz'
        $r.Healthy | Should-BeTrue
        $r.StatusCode | Should-Be 200
    }
    It 'reports a 503 as unhealthy' {
        (Test-OpsEndpoint -Uri 'https://down.example.com/healthz').Healthy | Should-BeFalse
    }
    It 'turns a network error into StatusCode 0 instead of throwing' {
        $r = Test-OpsEndpoint -Uri 'https://nowhere.invalid/healthz'
        $r.StatusCode | Should-Be 0
        $r.Error | Should-BeString 'No such host is known.'
    }
    It 'passes the timeout through to Invoke-WebRequest' {
        $null = Test-OpsEndpoint -Uri 'https://shop.example.com/healthz' -TimeoutSec 2
        Should-Invoke Invoke-WebRequest -ModuleName OpsKit -Times 1 -Exactly -ParameterFilter { $TimeoutSec -eq 2 }
    }
    It 'accepts HealthUrl from the pipeline by property name' {
        $results = [pscustomobject]@{ HealthUrl = 'https://a.example.com/' },
                   [pscustomobject]@{ HealthUrl = 'https://down.example.com/' } | Test-OpsEndpoint
        $results.Healthy -join ',' | Should-Be 'True,False'
    }
}

先定义默认 Mock(无过滤器);两个带过滤器的 Mock 为特定主机覆盖它。Mock 体中的 throw 模拟了 DNS 失败。

3. Invoke-OpsApi:不需要服务器就能测试重试、请求体和 -WhatIf

function Invoke-OpsApi {
    <#
    .SYNOPSIS
        Calls a JSON REST API with retries for HTTP 429 and 5xx responses.
    .EXAMPLE
        Invoke-OpsApi -Uri http://127.0.0.1:8088/api/servers
    #>
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)]
        [uri]$Uri,

        [ValidateSet('Get', 'Post', 'Put', 'Patch', 'Delete')]
        [string]$Method = 'Get',

        [object]$Body,

        [hashtable]$Headers = @{},

        [ValidateRange(0, 5)]
        [int]$MaxRetries = 3,

        [ValidateRange(0, 60000)]
        [int]$RetryDelayMs = 500
    )
    if ($Method -ne 'Get' -and -not $PSCmdlet.ShouldProcess($Uri.AbsoluteUri, "HTTP $Method")) {
        return
    }
    $request = @{ Uri = $Uri; Method = $Method; Headers = $Headers; ErrorAction = 'Stop' }
    if ($PSBoundParameters.ContainsKey('Body')) {
        $request.Body = $Body | ConvertTo-Json -Depth 10 -Compress
        $request.ContentType = 'application/json'
    }
    $attempt = 0
    while ($true) {
        $attempt++
        try {
            return Invoke-RestMethod @request
        } catch {
            $status = 0
            if ($_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode }
            $retryable = $status -eq 429 -or $status -ge 500
            if (-not $retryable -or $attempt -gt $MaxRetries) {
                throw
            }
            Write-OpsLog -Level Warning -Message "Attempt $attempt for $($Uri.AbsoluteUri) failed with HTTP $status; retrying"
            Start-Sleep -Milliseconds ($RetryDelayMs * [math]::Pow(2, $attempt - 1))
        }
    }
}
BeforeAll {
    Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force

    function New-HttpError([int]$Status) {
        $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$Status)
        [Microsoft.PowerShell.Commands.HttpResponseException]::new("Response status code does not indicate success: $Status", $response)
    }
}

Describe 'Invoke-OpsApi' {
    BeforeEach {
        Mock Start-Sleep -ModuleName OpsKit { }   # never really wait in a unit test
    }

    It 'returns the parsed response' {
        Mock Invoke-RestMethod -ModuleName OpsKit { [pscustomobject]@{ name = 'web-01' } }
        (Invoke-OpsApi -Uri 'http://127.0.0.1:8088/api/servers').name | Should-Be 'web-01'
    }
    It 'retries a 503 and then succeeds' {
        $script:calls = 0
        Mock Invoke-RestMethod -ModuleName OpsKit {
            $script:calls++
            if ($script:calls -lt 3) { throw (New-HttpError 503) }
            'ok'
        }
        Invoke-OpsApi -Uri 'http://127.0.0.1:8088/api/servers' -MaxRetries 3 | Should-Be 'ok'
        Should-Invoke Invoke-RestMethod -ModuleName OpsKit -Times 3 -Exactly
        Should-Invoke Start-Sleep -ModuleName OpsKit -Times 2 -Exactly
    }
    It 'does not retry a 404' {
        Mock Invoke-RestMethod -ModuleName OpsKit { throw (New-HttpError 404) }
        { Invoke-OpsApi -Uri 'http://127.0.0.1:8088/api/nope' } | Should-Throw -ExceptionMessage '*404*'
        Should-Invoke Invoke-RestMethod -ModuleName OpsKit -Times 1 -Exactly
    }
    It 'gives up after MaxRetries' {
        Mock Invoke-RestMethod -ModuleName OpsKit { throw (New-HttpError 429) }
        { Invoke-OpsApi -Uri 'http://127.0.0.1:8088/api/servers' -MaxRetries 2 } | Should-Throw
        Should-Invoke Invoke-RestMethod -ModuleName OpsKit -Times 3 -Exactly
    }
    It 'sends a body as compressed JSON' {
        Mock Invoke-RestMethod -ModuleName OpsKit { }
        Invoke-OpsApi -Uri 'http://127.0.0.1:8088/api/tags' -Method Post -Body @{ env = 'dev' }
        Should-Invoke Invoke-RestMethod -ModuleName OpsKit -ParameterFilter {
            $Method -eq 'Post' -and $Body -eq '{"env":"dev"}' -and $ContentType -eq 'application/json'
        }
    }
    It 'makes no call for a POST with -WhatIf' {
        Mock Invoke-RestMethod -ModuleName OpsKit { }
        Invoke-OpsApi -Uri 'http://127.0.0.1:8088/api/tags' -Method Post -Body @{ env = 'dev' } -WhatIf
        Should-NotInvoke Invoke-RestMethod -ModuleName OpsKit
    }
}
Describing Invoke-OpsApi
  [+] returns the parsed response 337ms
  [+] retries a 503 and then succeeds 257ms
  [+] does not retry a 404 68ms
  [+] gives up after MaxRetries 84ms
  [+] sends a body as compressed JSON 78ms
What if: Performing the operation "HTTP Post" on target "http://127.0.0.1:8088/api/tags".
  [+] makes no call for a POST with -WhatIf 36ms

如何验证:“retries a 503” 断言了 3 次调用 Invoke-RestMethod 以及 2 次调用 Start-Sleep —— 退避确实发生了,但不耗时。辅助函数 New-HttpError 构造的 HttpResponseException 与 pwsh 在 HTTP 错误时抛出的类型相同,因此被测代码中的 $_.Exception.Response.StatusCode 可以正常工作。生产用法:每个重试循环都应有这四个测试:成功、重试后成功、不可重试、放弃。

4. 用 InModuleScope 测私有函数,以及测试未安装的命令

BeforeAll {
    Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force
}

Describe 'Private helpers' {
    It 'are not exported' {
        Get-Command -Module OpsKit -Name Resolve-OpsPath -ErrorAction Ignore | Should-BeNull
    }
    It 'Resolve-OpsPath expands <Path>' -ForEach @(
        @{ Path = '~'; Expected = 'HOME' }
        @{ Path = '~/pslab/data'; Expected = 'HOME/pslab/data' }
    ) {
        InModuleScope OpsKit -Parameters @{ Path = $Path; Expected = $Expected } {
            $want = $Expected.Replace('HOME', $HOME).Replace('/', [IO.Path]::DirectorySeparatorChar)
            Resolve-OpsPath -Path $Path | Should-Be $want
        }
    }
    It 'Write-OpsLog writes one JSON line per entry' {
        $log = Join-Path $TestDrive 'log.jsonl'
        InModuleScope OpsKit -Parameters @{ Log = $log } {
            Write-OpsLog -Message 'one' -LogPath $Log
            Write-OpsLog -Message 'two' -Level Error -LogPath $Log
        }
        $lines = Get-Content -LiteralPath $log | ConvertFrom-Json
        $lines.Level | Should-BeCollection @('Information', 'Error')
    }
}
BeforeAll {
    Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force
    # Mock can only replace a command that exists. CI runners have no Az module,
    # so define a stand-in with the same parameter we use; Mock then replaces it.
    function global:Get-AzResource { param([hashtable]$Tag) }
}
AfterAll {
    Remove-Item -Path Function:\global:Get-AzResource -ErrorAction Ignore
}

Describe 'Get-OpsCloudInventory' {
    It 'flattens Azure resources and reads the env tag' {
        Mock Get-AzResource -ModuleName OpsKit {
            [pscustomobject]@{ Name = 'vm-web-01'; ResourceType = 'Microsoft.Compute/virtualMachines'; Location = 'canadacentral'; Tags = @{ app = 'opskit'; env = 'prod' } }
            [pscustomobject]@{ Name = 'st-logs'; ResourceType = 'Microsoft.Storage/storageAccounts'; Location = 'canadacentral'; Tags = $null }
        }
        $items = @(Get-OpsCloudInventory)
        $items.Count | Should-Be 2
        $items[0].Env | Should-Be 'prod'
        $items[1].Env | Should-BeNull
        Should-Invoke Get-AzResource -ModuleName OpsKit -Times 1 -Exactly -ParameterFilter { $Tag.app -eq 'opskit' }
    }
    It 'explains what is missing when Az.Resources is not available' {
        Mock Get-Command -ModuleName OpsKit -ParameterFilter { $Name -eq 'Get-AzResource' } { }
        { Get-OpsCloudInventory } | Should-Throw -ExceptionMessage '*needs the Az.Resources module*'
    }
}

在没有 Az 的运行器上,Mock Get-AzResource 会报 “Could not find Command Get-AzResource”(已验证该消息格式),所以测试先定义了一个只带代码所用参数的桩函数。第二个测试 Mock 了 Get-Command 本身 —— 只针对名称 Get-AzResource —— 以覆盖“模块缺失”分支。

目标:不联网测试 Invoke-OpsHealthCheck,并证明它会记录不健康的环境。环境:Pester 6.2.0、OpsKit。费用:无。

阅读函数:
function Invoke-OpsHealthCheck {
    <#
    .SYNOPSIS
        Checks the health URL of each configured environment.
    .EXAMPLE
        Invoke-OpsHealthCheck -Environment dev, staging
    #>
    [CmdletBinding()]
    param(
        [string]$ConfigPath = (Join-Path $HOME 'pslab' 'data' 'opskit.config.psd1'),

        [string[]]$Environment
    )
    $config = Get-OpsConfig -Path $ConfigPath
    $names = if ($Environment) { $Environment } else { $config.Environments.Keys | Sort-Object }
    foreach ($name in $names) {
        $target = Get-OpsConfig -Path $ConfigPath -Environment $name
        $result = Test-OpsEndpoint -Uri $target.HealthUrl -TimeoutSec $config.Health.TimeoutSec
        if (-not $result.Healthy) {
            Write-OpsLog -Level Warning -Message "$name is unhealthy: HTTP $($result.StatusCode) $($result.Error)"
        }
        [pscustomobject]@{
            PSTypeName  = 'OpsKit.HealthResult'
            Environment = $name
            Healthy     = $result.Healthy
            StatusCode  = $result.StatusCode
            Ms          = $result.Ms
        }
    }
}
编写测试 —— Mock Test-OpsEndpoint(OpsKit 内部调用的公有函数,所以要 -ModuleName OpsKit),用 $env:OPSKIT_LOG 把日志指向 TestDrive,并在 finally 中恢复:
BeforeAll {
    Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force
    $configPath = Join-Path $TestDrive 'opskit.config.psd1'
    @'
@{
    DefaultEnv   = 'dev'
    Environments = @{
        dev     = @{ Region = 'canadacentral'; HealthUrl = 'http://dev.example.com/healthz' }
        staging = @{ Region = 'ca-central-1'; HealthUrl = 'http://staging.example.com/healthz' }
    }
    Health       = @{ TimeoutSec = 3 }
}
'@ | Set-Content -LiteralPath $configPath
}

Describe 'Invoke-OpsHealthCheck' {
    BeforeEach {
        Mock Test-OpsEndpoint -ModuleName OpsKit {
            $code = if ($Uri.Host -like 'staging*') { 503 } else { 200 }
            [pscustomobject]@{ StatusCode = $code; Healthy = $code -eq 200; Ms = 12; Error = $null }
        }
    }
    It 'checks every environment in sorted order' {
        $results = Invoke-OpsHealthCheck -ConfigPath $configPath
        # Should-BeCollection ignores order, so compare a joined string when order matters.
        $results.Environment -join ',' | Should-Be 'dev,staging'
        $results.Healthy -join ',' | Should-Be 'True,False'
    }
    It 'uses the timeout from the configuration' {
        $null = Invoke-OpsHealthCheck -ConfigPath $configPath -Environment dev
        Should-Invoke Test-OpsEndpoint -ModuleName OpsKit -Times 1 -Exactly -ParameterFilter { $TimeoutSec -eq 3 }
    }
    It 'logs a warning line for an unhealthy environment' {
        $env:OPSKIT_LOG = Join-Path $TestDrive 'ops.log'
        try {
            $null = Invoke-OpsHealthCheck -ConfigPath $configPath -Environment staging
            $entry = Get-Content -LiteralPath $env:OPSKIT_LOG | ConvertFrom-Json
            $entry.Level | Should-Be 'Warning'
            $entry.Message | Should-BeLikeString 'staging is unhealthy: HTTP 503*'
        }
        finally {
            Remove-Item Env:OPSKIT_LOG
        }
    }
}
运行:
Invoke-Pester ./OpsKit/tests/Invoke-OpsHealthCheck.Tests.ps1 -Output Detailed
Describing Invoke-OpsHealthCheck
  [+] checks every environment in sorted order 88ms
  [+] uses the timeout from the configuration 39ms
  [+] logs a warning line for an unhealthy environment 48ms
试验:从 Mock 中去掉 -ModuleName OpsKit 再运行。测试现在调用真实的 Test-OpsEndpoint,去请求 dev.example.com —— 注意这有多慢、多不确定,然后改回来。
清理:无(TestDrive 自动删除,$env:OPSKIT_LOG 在 finally 中移除)。

案例 1:单元测试重启了真实服务

问题:在跳板机上运行测试套件时重启了 IIS。根因:Mock Restart-Service { } 声明时没有 -ModuleName;模块内部的调用打到了真实 cmdlet。修复:对模块内部调用的每一个 Mock 都加 -ModuleName,再加 Should-Invoke … -ModuleName,这样从未命中的 Mock 会让测试失败。单元测试在构建代理上运行,不要在服务器上运行。

案例 2:20 分钟的测试套件

问题:重试测试要跑好几分钟。根因:真实的 Start-Sleep 和指数退避。修复:Mock Start-Sleep -ModuleName OpsKit { } 并断言休眠次数;如果需要端到端证明,只保留一个使用极小 -RetryDelayMs 的慢速集成测试。

案例 3:升级到 Pester 6 后 40 个测试失败

问题:升级后大量测试报 “No mock for command … matched the call”。根因:它们依赖 v5 在过滤器不匹配时回落到真实命令。修复:为每个命令添加默认 Mock(通常是 { }),这也让测试对其允许的每一次调用都更诚实。

常见错误与修复

Expected Invoke-WebRequest to be called 1 time exactly, but was called 0 times

原因:调用发生在模块内部,而 Mock 或断言缺少 -ModuleName。修复:两者都加上 -ModuleName OpsKit。

RuntimeException: No mock for command 'X' matched the call: none of the parameter filters matched

原因:Pester 6 移除了回落。修复:在带过滤器的 Mock 之前加一个默认的 Mock X { };错误消息会列出已评估的过滤器和绑定的参数。

CommandNotFoundException: Could not find Command Get-AzResource

原因:无法 Mock 一个不存在的命令。修复:定义一个带所用参数的桩函数(全局,或通过 InModuleScope 放在模块内),再 Mock 它;在 AfterAll 中删除。

InModuleScope 中我的测试变量为 $null

原因:脚本块在模块的作用域中运行。修复:用 -Parameters @{ Path = $Path } 传值(它们会成为块内变量)。

Mock 在 ForEach-Object -Parallel 或作业中不生效

原因:每个运行空间有自己的会话状态。修复:把函数设计成并行部分可注入(提供 -ThrottleLimit 1 / 顺序执行路径,或一个脚本块参数),对顺序路径做单元测试;并行路径用集成测试覆盖。

命令行练习
1. 断言当只有一个备份时,Invoke-OpsBackup -Keep 1 从不调用 Remove-Item。
Mock Remove-Item -ModuleName OpsKit { }
$null = Invoke-OpsBackup -Source $source -Destination $destination -Keep 1
Should-NotInvoke Remove-Item -ModuleName OpsKit
2. 在 OpsKit 内部 Mock Get-Date,只有带 -Format 调用时才返回固定日期。
Mock Get-Date -ModuleName OpsKit -ParameterFilter { $Format } { '20261124-101500' }
Mock Get-Date -ModuleName OpsKit { [datetime]'2026-11-24T10:15:00' }   # 其他调用的默认 Mock
场景分析
一位同事想在 BeforeAll 中启动本地 HttpListener 来测试 Invoke-OpsApi;另一位只想用 Mock。你怎么建议?

两者都要,但层级不同。用 Mock 的单元测试在毫秒级证明逻辑(重试规则、请求体序列化、-WhatIf),且从不随机失败。再加一两个针对第 7 课 127.0.0.1 上模拟 API 的集成测试,证明真实的 HTTP 链路(请求头、JSON 解析、异常类型)。给集成测试打标签(-Tag Integration),让 CI 在单独的作业中运行,开发者本地可以排除它们。

已验证的教学视频

▶
Testing, Testing, 1...2...3: Using Pester for Infrastructure Validation by Brandon Olin — PowerShell.org
英文 · 测试设计、Mock 与测什么(大会演讲)
▶
PowerShell 7 Tutorials for Intermediates #5 : Pester (Testing) — JackedProgrammer
英文 · 包含 Mock 基础(Pester 5 语法)

两者都早于 Pester 6(没有 Should-Invoke,回落行为仍然存在)。没有找到讲解 Pester 6 Mock 变化的已验证视频。

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–25 秒
画面:Test-OpsEndpoint 向互联网发出请求;一个 Mock“插头”插到 Invoke-WebRequest 前面 —— 但在模块围墙之外,于是调用从旁边绕了过去。
旁白:Mock 必须放在调用发生的地方。
镜头 2 · 25–55 秒
画面:插头移到 OpsKit 围墙之内(-ModuleName);调用现在打到它上面;计数器跳动。
旁白:-ModuleName 把 Mock 注入模块;Should-Invoke 统计调用次数。
镜头 3 · 55–75 秒
画面:503、503、200 三个气泡;Start-Sleep 图标被划掉。
旁白:测试重试,但不用真等。
镜头 4 · 75–90 秒
画面:一个不匹配任何过滤器的调用撞上写着“no fall-through”的红墙。
旁白:在 Pester 6 中,每次调用都需要一个能应答它的 Mock。
或测验得分 ≥ 70%

模块 5 · 覆盖率与 CI 输出:代码覆盖率与测试结果文件

28:00 – 35:00 · CI 系统只认三样东西:退出码、测试结果 XML 文件和覆盖率 XML 文件。New-PesterConfiguration 能生成全部三样 —— 前提是选项设置正确
7 分钟New-PesterConfiguration · JaCoCo · NUnit★★★★☆
学习目标
  • 用 New-PesterConfiguration 构建一次运行:Run.Path、Run.PassThru、Output.Verbosity、CodeCoverage.*、TestResult.*。
  • 生成 JaCoCo(或 Cobertura)覆盖率和 NUnitXml / NUnit3 / JUnitXml 结果,读懂 CoveragePercent 和未覆盖的命令。
  • 控制进程结果:Run.Exit(退出码 = 失败测试数)、Run.Throw 和 -CI —— 并且知道覆盖率低于目标值本身不会让运行失败。
前置条件:模块 3–4。重要度:★★★★☆

是什么:配置对象

New-PesterConfiguration 返回一个分节的 [PesterConfiguration];每个选项都有 .Value、.Default 和 .Description。Invoke-Pester 的简单参数集(-Path -Output -CI -PassThru)适合快速运行;CI 使用配置对象。

节.选项用途默认值
Run.Path、Run.ExcludePath测试文件/目录.
Run.PassThru返回结果对象$false
Run.Exit测试失败时以非零退出码退出进程$false
Run.Throw测试失败时抛出异常(两者都设时优先抛出)$false
Output.VerbosityNone、Normal、Detailed、DiagnosticNormal
Output.CIFormatAuto、AzureDevops、GithubActions(错误注解)Auto
CodeCoverage.Enabled / Path / OutputFormat / OutputPath对这些文件统计覆盖率,输出 JaCoCo 或 Cobertura关闭;JaCoCo;coverage.xml
CodeCoverage.CoveragePercentTarget摘要中显示的目标值75
CodeCoverage.UseBreakpoints旧的基于断点的覆盖率$false(6.0 起基于分析器)
TestResult.Enabled / OutputFormat / OutputPathNUnitXml、NUnit2.5、NUnit3、JUnitXml关闭;NUnitXml;testResults.xml
Should.DisableV5禁止 Should -Be$false

为什么:给 CI 的三个信号

退出码决定步骤变红还是变绿。测试结果文件让 CI 系统展示测试名称、失败和趋势。覆盖率文件显示哪些行没有被任何测试执行。缺少其中任何一个,都是“CI 绿了但测试失败了”的常见原因。

怎么做:覆盖率衡量的是什么

Pester 统计你在 CodeCoverage.Path 中列出的文件里的命令(语句),并记录测试期间哪些被执行过。从 Pester 6 开始,它使用分析器跟踪器而不是给每条命令设一个断点,速度快得多。CodeCoverage.ExcludeTests(默认开启)让测试文件不计入数字。100% 命令覆盖率意味着每条语句至少运行过一次 —— 并不意味着每种分支组合或边界情况都被检查过。

何时用:退出码

配置测试失败时会怎样已验证
什么都不设打印摘要,进程退出码为 0✓ Result=Failed Failed=2,exit 0
Run.Exit = $true以失败测试数作为 exit 码✓ 2 个失败 → exit 2;后续行不再执行
Run.Throw = $true终止性错误 “Pester run failed, because 2 tests failed”✓
Invoke-Pester -CITestResult.Enabled + Run.Exit(不包含覆盖率)✓ 写出 testResults.xml,exit 2
覆盖率低于 CoveragePercentTarget只报告:“Covered 29.34% / 80%”;exit 0✓ —— 需要自己强制(模块 8)
常见误区① “测试失败时 pwsh -File run-tests.ps1 会以非零退出” —— 除非设置了 Run.Exit/Run.Throw 或自己检查 FailedCount,否则不会。② “-CI 会打开覆盖率” —— 在 Pester 6 中不会(帮助里写明了;请启用 CodeCoverage.Enabled)。③ “CoveragePercentTarget 会让构建失败” —— 它只是打印目标。④ “100% 覆盖率意味着没有缺陷” —— 模块 8 中 Should-All 的故事展示了一行被覆盖但值是错的;断言比百分比更重要。⑤ “结果文件无害” —— 它们包含主机名、用户名、操作系统和工作目录(见下面的 JUnit 文件);把它们当作构建产物,而不是公开文档。

图解:一次运行,三种输出

New-PesterConfigurationRun.Path = ./testsCodeCoverage.Path = Public, PrivateTestResult.OutputFormatRun.Exit / Throw / PassThru Invoke-Pester按文件:发现 → 运行分析器记录被覆盖文件中已执行的命令结果树 [Pester.Run] out/testResults.xmlNUnitXml · NUnit3 · JUnitXml → CI 的测试页 out/coverage.xmlJaCoCo · Cobertura → 覆盖率报告 / 行号栏标记 退出码Run.Exit:失败数 · 否则为 0(!)
图 5-1:退出码是 CI 唯一会自动据此行动的输出;请有意识地设置它

从测试运行到 CI 状态

就绪。
动画背后的真实机制 最后一个容器结束后,Pester 构建运行结果,写出配置的报告文件,然后应用失败策略:有 Run.Throw 就抛异常;有 Run.Exit 就以失败测试数调用 exit;否则直接返回(按该选项的说明,仍会设置 $LASTEXITCODE)。CI 步骤的状态来自运行它的 pwsh 进程的退出码。

命令表

命令用途
$c = New-PesterConfiguration从默认值开始
[PesterConfiguration]::Default.Run.Exit.Description读取某个选项的内置说明
$r = Invoke-Pester -Configuration $c运行(配合 Run.PassThru)
$r.Result、$r.FailedCount、$r.Failed结果、数量、失败的测试对象
$r.CodeCoverage.CoveragePercent、.CommandsMissed覆盖率数字和未执行的语句(File、Line、Command)
Invoke-Pester -CI快捷方式:TestResult + Exit

1. OpsKit 完整运行:覆盖率与 JUnit 结果

Import-Module Pester -MinimumVersion 6.0.0
Set-Location ./OpsKit
$config = New-PesterConfiguration
$config.Run.Path = './tests'
$config.Run.PassThru = $true
$config.Output.Verbosity = 'Normal'
$config.CodeCoverage.Enabled = $true
$config.CodeCoverage.Path = './Public', './Private'
$config.CodeCoverage.OutputFormat = 'JaCoCo'
$config.CodeCoverage.OutputPath = './out/coverage.xml'
$config.CodeCoverage.CoveragePercentTarget = 80
$config.TestResult.Enabled = $true
$config.TestResult.OutputFormat = 'JUnitXml'
$config.TestResult.OutputPath = './out/testResults.xml'
$result = Invoke-Pester -Configuration $config
'---'
$result | Select-Object Result, TotalCount, PassedCount, FailedCount, Duration | Format-List
$result.CodeCoverage | Select-Object CoveragePercent, CoveragePercentTarget, CommandsAnalyzedCount, CommandsExecutedCount, CommandsMissedCount | Format-List
$result.CodeCoverage.CommandsMissed | Select-Object File, Line, Command | Format-Table -AutoSize
Get-ChildItem ./out | Format-Table Name, Length
Running tests from 9 files.
Starting code coverage.
[+] C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsCloudInventory.Tests.ps1 1.6s (2 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsConfig.Tests.ps1 527ms (6 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsServer.Tests.ps1 606ms (9 tests)
What if: Performing the operation "HTTP Post" on target "http://127.0.0.1:8088/api/tags".
[+] C:\Users\labadmin\pslab\OpsKit\tests\Invoke-OpsApi.Tests.ps1 824ms (6 tests)
What if: Performing the operation "Create backup of 3 file(s) from C:\Users\labadmin\AppData\Local\Temp\Pester_1b2l\src-f89ec515-00aa-4828-bbec-78280a212207" on target "C:\Users\labadmin\AppData\Local\Temp\Pester_1b2l\dst-555e6637-ed4e-439c-b02b-e33c94f8af07\backup-20261124-101500.zip".
[+] C:\Users\labadmin\pslab\OpsKit\tests\Invoke-OpsBackup.Tests.ps1 742ms (7 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Invoke-OpsHealthCheck.Tests.ps1 376ms (3 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\OpsKit.Module.Tests.ps1 506ms (9 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Private.Tests.ps1 279ms (4 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Test-OpsEndpoint.Tests.ps1 471ms (5 tests)
Tests completed in 6.01s
Tests Passed: 51, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0
Processing code coverage result.
Covered 100% / 80%. 167 analyzed Commands in 9 Files.
---

Result      : Passed
TotalCount  : 51
PassedCount : 51
FailedCount : 0
Duration    : 00:00:06.0135538


CoveragePercent       : 100
CoveragePercentTarget : 80
CommandsAnalyzedCount : 167
CommandsExecutedCount : 167
CommandsMissedCount   : 0


Name            Length
----            ------
coverage.xml     15308
testResults.xml  24624

如何验证:9 个被覆盖文件(7 个公有、2 个私有)中共 167 条命令,全部执行。常见错误:把 CodeCoverage.Path 指向整个项目,测试和构建脚本会稀释数字。生产用法:每次运行(包括失败的)都把两个 XML 文件作为产物上传(模块 7 中的 if: always())。

2. 文件长什么样

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE report PUBLIC "-//JACOCO//DTD Report 1.1//EN" "report.dtd"[]>
<report name="Pester ()">
  <sessioninfo id="this" start="1795572296011" dump="1795572300600" />
  <package name="Private">
    <class name="Private/Resolve-OpsPath" sourcefilename="Resolve-OpsPath.ps1">
      <method name="Resolve-OpsPath" desc="()" line="9">
        <counter type="INSTRUCTION" missed="0" covered="5" />
        <counter type="LINE" missed="0" covered="5" />
        <counter type="METHOD" missed="0" covered="1" />
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<testsuites xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="junit_schema_4.xsd" name="Pester" tests="48" errors="0" failures="0" disabled="0" time="4.589">
  <testsuite name="C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsConfig.Tests.ps1" tests="6" errors="0" failures="0" hostname="LAB-01" id="0" skipped="0" disabled="0" … time="1.090" timestamp="2026-11-24T21:04:56">
    <properties>
      <property name="user-domain" value="LAB" />
      <property name="machine-name" value="LAB-01" />
      <property name="os-version" value="10.0.26300" />
      <property name="framework-version" value="6.2.0" />
      <property name="user" value="labadmin" />
      <property name="cwd" value="C:\Users\labadmin\pslab\OpsKit" />
      <property name="clr-version" value="10.0.15" />
    </properties>

这个文件来自更早的一次 48 个测试的运行(当时还没有加入 Get-OpsCloudInventory 的测试)。JaCoCo 路径是相对路径(Private/Resolve-OpsPath);Pester 6 让覆盖率路径相对于 Run.RepoRoot(从最近的 .git 目录推断)。

3. 覆盖率低于目标不会让运行失败

Import-Module Pester -MinimumVersion 6.0.0
Set-Location ./OpsKit
$config = New-PesterConfiguration
$config.Run.Path = './tests/Get-OpsServer.Tests.ps1', './tests/Get-OpsConfig.Tests.ps1'
$config.Run.Exit = $true
$config.Output.Verbosity = 'Normal'
$config.CodeCoverage.Enabled = $true
$config.CodeCoverage.Path = './Public', './Private'
$config.CodeCoverage.OutputPath = './out/coverage-partial.xml'
$config.CodeCoverage.CoveragePercentTarget = 80
Invoke-Pester -Configuration $config
Running tests from 2 files.
Starting code coverage.
[+] C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsServer.Tests.ps1 1.07s (9 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsConfig.Tests.ps1 347ms (6 tests)
Tests completed in 1.44s
Tests Passed: 15, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0
Processing code coverage result.
Covered 29.34% / 80%. 167 analyzed Commands in 9 Files.

4. 退出码:Run.Exit、Run.Throw 与默认

Import-Module Pester -MinimumVersion 6.0.0
$c = New-PesterConfiguration
$c.Run.Path = './demo/Order.Tests.ps1'
$c.Output.Verbosity = 'None'
$c.Run.Exit = $true
Invoke-Pester -Configuration $c
'not reached'
(no console output: Verbosity None)
exit code of the pwsh process: 2
Import-Module Pester -MinimumVersion 6.0.0
$c = New-PesterConfiguration
$c.Run.Path = './demo/Order.Tests.ps1'
$c.Output.Verbosity = 'None'
$c.Run.Throw = $true
try { Invoke-Pester -Configuration $c } catch { "caught: $($_.Exception.Message)" }
'--- default: no Exit, no Throw'
$c = New-PesterConfiguration
$c.Run.Path = './demo/Order.Tests.ps1'
$c.Output.Verbosity = 'None'
$c.Run.PassThru = $true
$r = Invoke-Pester -Configuration $c
"Result=$($r.Result) Failed=$($r.FailedCount)"
caught: Pester run failed, because 2 tests failed
--- default: no Exit, no Throw
Result=Failed Failed=2
Import-Module Pester -MinimumVersion 6.0.0
Invoke-Pester -Path ./demo/Order.Tests.ps1 -CI -Output None
exit code of the pwsh process: 2   (testResults.xml written to the current folder, NUnit 2.5 format; no coverage.xml)
Import-Module Pester -MinimumVersion 6.0.0
$c = [PesterConfiguration]::Default
$c.CodeCoverage.Enabled.Description
$c.Run.Exit.Description
$c.Run.Throw.Description
$c.TestResult.OutputFormat.Description
$c.CodeCoverage.OutputFormat.Description
$c.CodeCoverage.CoveragePercentTarget.Description
$c.Should.DisableV5.Description
Get-Help Invoke-Pester -Parameter CI | Out-String
Enable CodeCoverage.
Exit with non-zero exit code when the test run fails. Exit code is always set to `$LASTEXITCODE` even when this option is `$false`. When used together with Throw, throwing an exception is preferred.
Throw an exception when test run fails. When used together with Exit, throwing an exception is preferred.
Format to use for test result report. Possible values: NUnitXml, NUnit2.5, NUnit3 or JUnitXml
Format to use for code coverage report. Possible values: JaCoCo, Cobertura
Target percent of code coverage that you want to achieve, default 75%.
Disables usage of Should -Be assertions, that are replaced by Should-Be in version 6.

-CI [<SwitchParameter>]
    Enable Test Results and Exit after Run.
    
    Equivalent to setting:
        TestResult.Enabled = $true
        Run.Exit = $true
    
    To also enable CodeCoverage use this configuration option:
        CodeCoverage.Enabled = $true
    
    Required?                    false
    Position?                    named
    Default value                False
    Accept pipeline input?       false
    Aliases                      
    Accept wildcard characters?  false

目标:写一个可供 CI 调用的 tests/run.ps1:生成结果和覆盖率文件,测试失败或覆盖率过低时以非零退出码结束。环境:Pester 6.2.0。费用:无。

编写:
#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.0.0' }
param([int]$Threshold = 80)
$c = New-PesterConfiguration
$c.Run.Path = "$PSScriptRoot"
$c.Run.PassThru = $true
$c.CodeCoverage.Enabled = $true
$c.CodeCoverage.Path = "$PSScriptRoot/../Public", "$PSScriptRoot/../Private"
$c.CodeCoverage.OutputPath = "$PSScriptRoot/../out/coverage.xml"
$c.TestResult.Enabled = $true
$c.TestResult.OutputPath = "$PSScriptRoot/../out/testResults.xml"
$r = Invoke-Pester -Configuration $c
if ($r.FailedCount -gt 0) { exit 1 }
if ($r.CodeCoverage.CoveragePercent -lt $Threshold) { Write-Warning "coverage $($r.CodeCoverage.CoveragePercent)% below $Threshold%"; exit 3 }
exit 0
像 CI 一样运行:pwsh -NoProfile -NonInteractive -File ./OpsKit/tests/run.ps1; "exit=$LASTEXITCODE" → exit=0。
故意降低覆盖率:暂时把 Invoke-OpsApi.Tests.ps1 移出目录,用 -Threshold 90 运行。剩下的测试全部通过,但覆盖率下降,脚本以 3 退出:
Tests Passed: 45, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0
Processing code coverage result.
Covered 85.63% / 75%. 167 analyzed Commands in 9 Files.
WARNING: coverage 85.6287425149701% below 90%

注意摘要里显示的仍是 Pester 自己的默认目标(75%),因为脚本没有设置 CoveragePercentTarget;真正起决定作用的是你的阈值检查。少了一个测试文件就掉了 14 个百分点:Invoke-OpsApi 的 6 个测试是唯一覆盖其重试循环的测试。

查看未覆盖的行:$r.CodeCoverage.CommandsMissed | Format-Table File, Line, Command(加上 Run.PassThru 并保留 $r)。
清理:把测试文件移回去;Remove-Item ./OpsKit/out -Recurse。

案例 1:流水线是绿的,测试是红的

问题:一条流水线连续两周保持绿色,而有 3 个测试失败。根因:步骤运行的是 pwsh -c "Invoke-Pester ./tests" —— 失败被打印出来,但退出码是 0。修复:Run.Exit = $true(或 -CI),再加上测试结果文件,让 CI 系统醒目地显示失败。

案例 2:覆盖率一夜之间从 85% “跌”到 40%

问题:没有人删测试。根因:有人把 CodeCoverage.Path 设成了 '.',构建脚本和随项目携带的模块都进了分母。修复:只列出模块的源码目录,并保持 ExcludeTests 开启。

案例 3:结果文件暴露了内部主机名

问题:一个开源项目把 NUnit 结果附在公开的发布中。根因:结果文件包含机器名、用户和工作目录。修复:把它们作为有保留期限的 CI 产物,而不是发布附件。

常见错误与修复

覆盖率为 0% / “0 analyzed Commands”

原因:CodeCoverage.Path 指向的文件并不是测试导入的那些(out/stage 中的副本、PSModulePath 中的其他模块版本)。修复:从你统计覆盖率的同一目录按路径导入模块。

CI 系统中看不到测试

原因:报告格式与 CI 的报告器不匹配(JUnit 与 NUnit),或失败时没有上传文件。修复:让 TestResult.OutputFormat 与报告器匹配;用 if: always() 上传。

配置拒绝了某个值(Pester 6.2)

原因:6.2 会校验配置值而不是悄悄忽略(发布说明)。修复:阅读 [PesterConfiguration]::Default.节.选项.Description 了解允许的值。

覆盖率数字与 Pester 5 不同

原因:Pester 6 默认使用分析器跟踪器。修复:接受新的基线,或临时设置 CodeCoverage.UseBreakpoints = $true 进行对比。

命令行练习
1. 生成 Cobertura 覆盖率和 NUnit3 结果,而不是默认格式。
$c = New-PesterConfiguration
$c.Run.Path = './OpsKit/tests'
$c.CodeCoverage.Enabled = $true; $c.CodeCoverage.Path = './OpsKit/Public', './OpsKit/Private'
$c.CodeCoverage.OutputFormat = 'Cobertura'
$c.TestResult.Enabled = $true; $c.TestResult.OutputFormat = 'NUnit3'
Invoke-Pester -Configuration $c
2. 从 PassThru 结果中打印覆盖率最差的三个文件。
$r.CodeCoverage.CommandsMissed | Group-Object File -NoElement | Sort-Object Count -Descending | Select-Object -First 3
场景分析
管理层要求 OpsKit 达到“100% 覆盖率”。你已经有 100% 命令覆盖率了。任务完成了吗?

没有。命令覆盖率只证明每条语句运行过,不证明测试检查了正确的结果,也不证明每种分支组合和错误路径都被执行过。OpsKit 覆盖率是 100%,但一个真实缺陷之所以被发现,只是因为 Should-All 对空集合会失败(模块 8)。更好的目标:每个公有函数都有覆盖正常路径、每种文档化错误、-WhatIf 和边界值的测试;覆盖率是发现未测代码的烟雾报警器,而不是质量分数。

已验证的教学视频

▶
GitHub Actions for Fun and Profit by Adam Driscoll — PowerShell.org
英文 · 在 CI 中运行 PowerShell 测试

没有找到专门讲解 Pester 6 配置、覆盖率格式或退出码的已验证视频;请参考 Pester 文档和本模块经过验证的输出。

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–30 秒
画面:Invoke-Pester 引出三根管道:XML 结果、XML 覆盖率、退出码。
旁白:CI 需要三样东西。
镜头 2 · 30–60 秒
画面:两个测试失败,流水线依然是绿的;接着 Run.Exit 把它翻成红色。
旁白:没有 Run.Exit,失败的测试照样以 0 退出。
镜头 3 · 60–90 秒
画面:“Covered 29% / 80%” 且 exit 0;构建脚本中的检查把它变红。
旁白:覆盖率要靠你自己强制执行。
或测验得分 ≥ 70%

模块 6 · 性能:Measure-Command、集合构建与管道开销

35:00 – 42:00 · 大多数慢的 PowerShell 代码都来自少数几种写法:用 += 扩展数组、用 += 拼接字符串、让海量集合逐个经过管道中的脚本块,以及在管道的错误一侧筛选。先测量,再修正写法
7 分钟Measure-Command★★★☆☆
学习目标
  • 正确地用 Measure-Command 计时(预热、多次取最好、输出被丢弃、作用域影响)。
  • 比较数组 +=、List[T].Add() 和管道捕获($a = foreach (…) { … }),以及字符串 +=、StringBuilder 和 -join。
  • 比较 ForEach-Object、foreach 与 .ForEach(),以及 Where-Object 与 .Where()。
  • 践行尽早筛选:由提供程序执行的 -Filter 胜过 Where-Object,而 -Include 可能比两者都慢。
前置条件:第 2 课(集合、循环)。重要度:★★★☆☆(大数据量时很重要;12 台服务器时无关紧要)

是什么:时间都花在哪里

写法为什么慢更好的做法
循环中 $a += $x数组长度固定:每次 += 都分配新数组并复制全部元素(O(n²))$a = foreach (…) { $x } 或 List[T]
循环中 $s += "…"字符串不可变:每次 += 都复制整个字符串对捕获的集合做一次 -join,或用 StringBuilder
10 万个元素 … | ForEach-Object { }管道开销 + 每个元素一次脚本块调用对已在内存中的数据用 foreach 语句
Get-ChildItem | Where-Object每个文件先变成对象,然后大部分被丢弃-Filter(由提供程序筛选)
Get-ChildItem -Include实现为后置过滤,并有额外的路径处理一个模式就够时用 -Filter

为什么:实验机上的实测数据

7.6.10 上的真实耗时(3 次取最好,单位毫秒;你的数字会不同,关键是比例):

20,000 个元素ms100,000 个元素ms
数组 +=1446ForEach-Object { }181.5
List[int].Add()297.7foreach ($x in $data) { }38.3
$a = foreach (…) { $i }22.1$data.ForEach({ })107.9
字符串 +=1046Where-Object { }265.0
StringBuilder113.9$data.Where({ })80.3
对捕获的行 -join41.2foreach + if51.4

两个值得记住的意外:管道捕获($a = foreach …)在这里比 List[int].Add() 快 10 倍以上,因为每次 .Add() 都是从脚本发起的 .NET 方法调用,要经过绑定器开销,而 foreach 语句是原生收集输出;出于同样的原因,-join 也胜过了 StringBuilder。

怎么做:正确地测量

  • 先预热一次(第一次运行要付出编译和类型加载的代价)。
  • 取 N 次中最好的(或中位数);单个数字是噪音。
  • Measure-Command 会丢弃脚本块的输出(好处是排除了格式化开销),并在当前作用域中运行(演示中 $x 被改成了 2)。
  • 用真实规模测量:12 个元素时什么都不重要;10 万个时就重要了。

何时用:只优化热点路径

对几百个对象,可读的管道完全没问题。当循环要处理几万个元素、函数在紧密循环中被调用,或分析(对脚本各部分用 Measure-Command)显示时间耗在哪里时,再使用这些写法。在测试中,Should-BeFasterThan 可以守住时间预算,但在共享的 CI 运行器上计时断言不稳定 —— 预算要给得宽松。

常见误区① “List[T] 永远是构建集合最快的方式” —— 在这里捕获 foreach 的输出快了 13 倍;需要从多处添加或需要 .Remove() 时再用 List[T]。② “.Where() 和 Where-Object 一样” —— .Where() 需要整个集合都在内存中,但跳过了管道(这里快 3.3 倍)。③ “-Include 就是尽早筛选” —— 它是最慢的选项(134 ms,对比 Where-Object 的 64 ms 和 -Filter 的 4.4 ms)。④ “Measure-Command 会显示我的输出” —— 它会吞掉输出;如需包含显示开销,用 Measure-Command { … | Out-Default }。⑤ “7.x 已经修复了 +=” —— 最近的版本中它变快了,但仍是所测选项中最慢的。

图解:为什么 += 是平方级的

$a += $i(每次都复制) 1 1 2 1 2 3 1 2 3 4 n 次分配,1+2+…+n 次复制 ≈ n²/2 20,000 个元素:1446 ms $a = foreach (…) { $i }(一次性收集) 管道输出缓冲区按几何级数增长 最后生成一个 object[] 均摊 O(n) 20,000 个元素:22.1 ms
图 6-1:结果相同,分配策略不同;差距随 n 增大

图解:尽早筛选

2,000 个文件 2,000 个 FileInfo 对象→ Where-Object → 200(64 ms) -Filter *.log 在文件系统层→ 只有 200 个对象(4.4 ms) -Include *.log(需要 path\*)后置过滤 + 路径处理:134 ms
图 6-2:-Filter 交给提供程序(操作系统 API)处理;-Include 和 Where-Object 处理的是已经创建好的对象

开销赛跑:结果相同,代价不同

就绪。
动画背后的真实机制 引擎把脚本块编译成表达式树并缓存;foreach 语句在一个编译好的块内运行,而 ForEach-Object 通过管道处理器为每个输入对象调用一次脚本块。对 .NET 对象的方法调用($list.Add())要经过 PowerShell 的动态绑定器。数组 += 每次都创建一个新的 object[]。

命令表

命令 / 写法用途
Measure-Command { … }返回 TimeSpan;输出被丢弃
(Measure-Command { … }).TotalMilliseconds一个数字
[Diagnostics.Stopwatch]::StartNew()在脚本内部为各段计时(OpsKit 的 Test-OpsEndpoint 就用了它)
$list = [System.Collections.Generic.List[string]]::new()可增长的强类型列表
$a = foreach ($x in $in) { f $x }从循环构建数组的最快方式
[System.Text.StringBuilder]::new()、$null = $sb.Append()从多处追加大量字符串
$lines -join "`n"一次性连接
$data.Where({ … }, 'First', 5)带模式的内存筛选(First、Last、Until、SkipUntil、Split)
Get-ChildItem -Filter '*.log'提供程序侧筛选

1. 构建集合和字符串

$n = 20000
function Measure-Ms([scriptblock]$Block, [int]$Repeat = 3) {
    # best of N runs, in milliseconds
    $best = [double]::MaxValue
    for ($i = 0; $i -lt $Repeat; $i++) {
        $ms = (Measure-Command $Block).TotalMilliseconds
        if ($ms -lt $best) { $best = $ms }
    }
    [math]::Round($best, 1)
}
$null = Measure-Ms { 1..100 | ForEach-Object { $_ } } 1   # warm-up

[pscustomobject]@{ Test = 'array +=';                     Ms = Measure-Ms { $a = @(); foreach ($i in 1..$n) { $a += $i } } 1 }
[pscustomobject]@{ Test = 'List[int].Add()';              Ms = Measure-Ms { $l = [System.Collections.Generic.List[int]]::new(); foreach ($i in 1..$n) { $l.Add($i) } } }
[pscustomobject]@{ Test = '$a = foreach (...) { $i }';    Ms = Measure-Ms { $a = foreach ($i in 1..$n) { $i } } }
[pscustomobject]@{ Test = 'string +=';                    Ms = Measure-Ms { $s = ''; foreach ($i in 1..$n) { $s += "line $i`n" } } 1 }
[pscustomobject]@{ Test = 'StringBuilder';                Ms = Measure-Ms { $sb = [System.Text.StringBuilder]::new(); foreach ($i in 1..$n) { $null = $sb.Append("line $i`n") } } }
[pscustomobject]@{ Test = '-join';                        Ms = Measure-Ms { $s = $(foreach ($i in 1..$n) { "line $i" }) -join "`n" } }
Test                           Ms
----                           --
array +=                  1446.00
List[int].Add()            297.70
$a = foreach (...) { $i }   22.10
string +=                 1046.00
StringBuilder              113.90
-join                       41.20

2. 对 100,000 个数字的循环与筛选

$n = 100000
function Measure-Ms([scriptblock]$Block, [int]$Repeat = 3) {
    $best = [double]::MaxValue
    for ($i = 0; $i -lt $Repeat; $i++) {
        $ms = (Measure-Command $Block).TotalMilliseconds
        if ($ms -lt $best) { $best = $ms }
    }
    [math]::Round($best, 1)
}
$data = 1..$n
$null = Measure-Ms { $data | Where-Object { $_ % 2 } } 1   # warm-up

[pscustomobject]@{ Test = 'ForEach-Object { }';          Ms = Measure-Ms { $data | ForEach-Object { $_ * 2 } } }
[pscustomobject]@{ Test = 'foreach ($x in $data) { }';   Ms = Measure-Ms { foreach ($x in $data) { $x * 2 } } }
[pscustomobject]@{ Test = '$data.ForEach({ })';          Ms = Measure-Ms { $data.ForEach({ $_ * 2 }) } }
[pscustomobject]@{ Test = 'Where-Object { }';            Ms = Measure-Ms { $data | Where-Object { $_ % 7 -eq 0 } } }
[pscustomobject]@{ Test = '$data.Where({ })';            Ms = Measure-Ms { $data.Where({ $_ % 7 -eq 0 }) } }
[pscustomobject]@{ Test = 'foreach + if';                Ms = Measure-Ms { foreach ($x in $data) { if ($x % 7 -eq 0) { $x } } } }
Test                          Ms
----                          --
ForEach-Object { }        181.50
foreach ($x in $data) { }  38.30
$data.ForEach({ })        107.90
Where-Object { }          265.00
$data.Where({ })           80.30
foreach + if               51.40

3. 文件系统上的尽早筛选,以及 Measure-Command 的作用域

# Filter left: build a folder with 2,000 files, 200 of them .log
$dir = Join-Path $PWD 'tmp/perf'
$null = New-Item -ItemType Directory -Path $dir -Force
foreach ($i in 1..2000) {
    $ext = if ($i % 10 -eq 0) { 'log' } else { 'txt' }
    [System.IO.File]::WriteAllText((Join-Path $dir "f$i.$ext"), 'x')
}
function Measure-Ms([scriptblock]$Block, [int]$Repeat = 3) {
    $best = [double]::MaxValue
    for ($i = 0; $i -lt $Repeat; $i++) {
        $ms = (Measure-Command $Block).TotalMilliseconds
        if ($ms -lt $best) { $best = $ms }
    }
    [math]::Round($best, 1)
}
$null = Get-ChildItem $dir
[pscustomobject]@{ Test = 'Get-ChildItem | Where-Object Extension'; Count = @(Get-ChildItem $dir | Where-Object Extension -eq '.log').Count; Ms = Measure-Ms { Get-ChildItem $dir | Where-Object Extension -eq '.log' } }
[pscustomobject]@{ Test = 'Get-ChildItem -Filter *.log';           Count = @(Get-ChildItem $dir -Filter '*.log').Count;                  Ms = Measure-Ms { Get-ChildItem $dir -Filter '*.log' } }
[pscustomobject]@{ Test = 'Get-ChildItem -Include *.log';          Count = @(Get-ChildItem "$dir/*" -Include '*.log').Count;            Ms = Measure-Ms { Get-ChildItem "$dir/*" -Include '*.log' } }
Remove-Item -LiteralPath $dir -Recurse -Force
# Measure-Command hides output, and runs in the current scope
$x = 1
$t = Measure-Command { $x = 2; 'you will not see this' }
"x after Measure-Command: $x; elapsed type: $($t.GetType().Name)"
Test                                   Count     Ms
----                                   -----     --
Get-ChildItem | Where-Object Extension   200  64.40
Get-ChildItem -Filter *.log              200   4.40
Get-ChildItem -Include *.log             200 134.20
x after Measure-Command: 2; elapsed type: TimeSpan

如何验证:三种写法返回的都是同样的 200 个文件 —— 比较耗时之前一定先检查结果数量。最后一行证明 Measure-Command 在当前作用域中运行($x 变成了 2)并吞掉了输出。常见错误:只计时一次,而且包含了首次编译。生产用法:修改代码之前,先用 Stopwatch 包住可疑的热点并记录毫秒数(第 5 课的 JSON 日志)。

目标:为放大到 61,100 行的 access.log 加速一个日志汇总脚本。环境:pwsh 7.6。费用:~/pslab/tmp 中几 MB 空间。

生成大文件:
$src = Get-Content ~/pslab/data/access.log
$big = foreach ($i in 1..100) { $src }
Set-Content ~/pslab/tmp/big.log -Value $big
(Get-Content ~/pslab/tmp/big.log).Count
61100
慢版本:
Measure-Command {
    $errors = @()
    Get-Content ~/pslab/tmp/big.log | ForEach-Object {
        if ($_ -match '" 5\d\d ') { $errors += $_ }
    }
}
更快的版本 —— 比较三者,并检查每个都返回 2,000 行(20 × 100):
Measure-Command { $errors = foreach ($l in [IO.File]::ReadLines("$HOME/pslab/tmp/big.log")) { if ($l -match '" 5\d\d ') { $l } } }
Measure-Command { $errors = (Get-Content ~/pslab/tmp/big.log).Where({ $_ -match '" 5\d\d ' }) }
Measure-Command { $errors = Select-String -Path ~/pslab/tmp/big.log -Pattern '" 5\d\d ' }
记录你的数字,做成“原理”页那样的表格;指出哪个版本在速度与可读性之间平衡得最好。
清理:Remove-Item ~/pslab/tmp/big.log

案例 1:一份资源清单报表跑了 40 分钟

问题:一份覆盖 180,000 个 Azure 资源的夜间报表要跑 40 分钟。根因:循环里写的是 $report += [pscustomobject]@{…}。修复:$report = foreach ($r in $resources) { [pscustomobject]@{…} } —— 运行时间降到两分钟以内;瓶颈变成了 API 调用,这正是第 7 课的分页和 Resource Graph 能帮上忙的地方。

案例 2:清理任务压垮了文件服务器

问题:Get-ChildItem \\fs\share -Recurse | Where-Object Extension -eq '.tmp' 要跑几个小时。修复:Get-ChildItem \\fs\share -Recurse -Filter *.tmp -File —— 由 SMB 服务器筛选,经过网络的条目少得多。

案例 3:计时测试在 CI 中随机失败

问题:{ Get-OpsServer } | Should-BeFasterThan 50ms 在共享运行器上时好时坏。修复:从单元测试中移除严格的计时断言;用单独的、重复多次的基准作业和宽松的预算跟踪性能。

常见错误与修复

Measure-Command 显示耗时很短,但脚本感觉很慢

原因:慢的是输出格式化或宿主(控制台渲染),而 Measure-Command 不包含这部分。修复:测量 { … | Out-Default },或把结果写入文件而不是控制台。

Method invocation failed because [System.Object[]] does not contain a method named 'Add'

原因:对普通数组调用 .Add()。修复:创建 List[T],或使用管道捕获。

函数返回后我的 List[int] 变成了 object[]

原因:返回集合时会被展开到管道中。修复:需要保留类型时用 return ,$list 或 Write-Output -NoEnumerate $list。

.Where() 返回的是 Collection`1,不是数组

原因:.Where() 和 .ForEach() 返回 Collection[psobject]。它在索引和 .Count 方面与数组表现一致;如果某个 API 需要 object[],用 @(…) 转换。

命令行练习
1. 写一个 Measure-Best 辅助函数,返回 N 次运行中最好的毫秒数。
function Measure-Best([scriptblock]$Block, [int]$Repeat = 5) {
    ($(foreach ($i in 1..$Repeat) { (Measure-Command $Block).TotalMilliseconds }) | Measure-Object -Minimum).Minimum
}
2. 不用 += 改写 $out = @(); foreach ($s in Get-OpsServer) { if ($s.Monitored) { $out += $s.Name } }。
$out = foreach ($s in Get-OpsServer) { if ($s.Monitored) { $s.Name } }
场景分析
一位同事“为了性能”把 OpsKit 中所有 Where-Object 都换成了 .Where()。你会批准吗?

不会全盘批准。OpsKit 的集合很小(12 台服务器),可读性和流式处理比微秒级差距更重要。.Where() 需要完整集合都在内存中,并打断了管道的流式处理;Where-Object 适用于任何管道输入。只在经过测量的、处理大型内存集合的热点路径中批准,并要求拉取请求说明中附上基准数据。

已验证的教学视频

▶
Make Your PowerShell Scripts Faster! — Jeff Brown Tech
英文 · 数组追加、抑制输出、管道
▶
#PowerShell Generic List in seconds - performance comparison between array and list at the end — Kamil Pro
英文 · 短视频;数组与 List[T] 对比

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–30 秒
画面:一个数组盒子一次又一次被复制进稍大一点的盒子;计时器飞快跳动。
旁白:+= 每次都复制全部内容。
镜头 2 · 30–60 秒
画面:柱状图 1446 / 298 / 22 ms。
旁白:让 foreach 语句去收集结果。
镜头 3 · 60–90 秒
画面:一台文件服务器;-Filter 箭头止步于服务器,Where-Object 箭头把 2,000 个盒子搬过网络。
旁白:在源头尽早筛选。
或测验得分 ≥ 70%

模块 7 · 安全与发布:签名、语义化版本、变更日志与 GitHub Actions 工作流

42:00 – 50:00 · 一次发布就是一个承诺:这份代码、这个版本、按这种方式构建和测试、由我们发布。Authenticode 签名、受限语言模式、语义化版本、变更日志和 CI 工作流,是 PowerShell 团队兑现这个承诺的方式
8 分钟Authenticode · SemVer · GitHub Actions★★★★☆
学习目标
  • 用 Get-AuthenticodeSignature 检查签名,了解 Set-AuthenticodeSignature 如何用代码签名证书签署脚本,以及 AllSigned 和 RemoteSigned 的要求。
  • 解释受限语言模式(CLM):它阻止什么、何时被强制(App Control/WDAC、AppLocker),以及为什么模块不应无谓依赖完整语言特性。
  • 用 SemVer 管理模块版本:ModuleVersion([version],不带标签)加 PrivateData.PSData.Prerelease;用 [semver] 比较版本;维护 CHANGELOG.md。
  • 编写 .github/workflows/opskit.yml:Windows/Ubuntu/macOS 矩阵、shell: pwsh、固定工具版本、分析、测试、上传结果,并在打标签时用 API 密钥机密发布。
前置条件:第 1 课(执行策略)、第 4 课(清单、PSResourceGet)、第 7 课(机密)。重要度:★★★★☆

是什么:三层信任

层次回答的问题PowerShell 机制
完整性 + 来源自 X 签名以来,这个文件被改过吗?位于 .ps1/.psm1/.psd1 末尾的 Authenticode 签名块;Get-AuthenticodeSignature → Valid、NotSigned、HashMismatch、NotTrusted
策略这个文件可以在这里运行吗?执行策略(AllSigned:每个脚本都由可信发布者签名;RemoteSigned:下载的脚本需签名)—— 是安全带,不是安全边界(第 1 课)
强制执行不可信代码能做什么?App Control for Business(WDAC)/ AppLocker 让不可信脚本运行在 ConstrainedLanguage 中;可信(被允许签名的)代码运行在 FullLanguage 中

为什么:一张表看懂受限语言模式

CLM 中允许CLM 中被阻止(已在 7.6.10 上验证)
cmdlet 和函数、管道、核心类型([string]、[int]、[hashtable]、数组)非核心类型上的方法:[System.IO.File]::ReadAllText() → “Method invocation is supported only on core types in this language mode.”
循环、条件、变量Add-Type → “Definition of new types is not supported in this language mode.”
策略允许的模块[pscustomobject]@{…} → “Cannot convert value to type … Only core types are supported in this language mode.”

OpsKit 用到了 [pscustomobject]、[System.IO.Compression.ZipFile] 和 [System.IO.Path]。只要 OpsKit 经过签名并被组织的 App Control 策略允许,就没有问题 —— 那样即使在锁定的机器上它也运行在 FullLanguage 中。未签名时,它在那里会失败。

怎么做:PowerShell 模块的 SemVer

变更升级OpsKit 示例
破坏性变更:删除/重命名函数或参数、改变输出类型MAJOR0.5.0 → 1.0.0(1.0 = “公共 API 从此稳定”)
新增函数或可选参数MINOR1.0.0 → 1.1.0 新增 Get-OpsReport
修复缺陷,API 不变PATCH1.1.0 → 1.1.1
预发布标签ModuleVersion = '1.0.0' + Prerelease = 'rc1' → 1.0.0-rc1

ModuleVersion 是 [version](1.0.0-rc1 会被拒绝 —— 已验证);标签放在 PrivateData.PSData.Prerelease 中。PowerShell 的 [semver] 类型能正确比较:1.0.0-rc1 < 1.0.0。注意标签:rc.2 < rc.10(数字标识符),但 rc2 < rc10 为 False(按字符串比较)—— 请使用点分标签或补零。另外绝不要比较版本字符串:'1.10.0' -gt '1.9.0' 为 False。

何时用:发布工作流

每次推送和拉取请求时:在三个操作系统上分析和测试。打上 v1.0.0 这样的标签时:再次运行测试,检查标签与清单版本一致,打包,并用存放在 GitHub 环境机密中的 API 密钥发布(受保护的环境 = 发布前需要人工批准)。采用 Keep a Changelog 格式的 CHANGELOG.md 记录面向用户的变更。

常见误区① “签了名就安全” —— 它只表示自已知发布者签名以来未被修改;恶意软件也可以签名。② “CI 里用 Bypass 就绕过了 App Control” —— 执行策略和 App Control 是两回事;CLM 无论如何都会被强制。③ “ModuleVersion = '1.0.0-rc1'” —— 无效;请用 Prerelease。④ “打标签就发布清单里的版本” —— 要检查标签与清单一致,否则会在 v1.0.0 标签下发布 0.5.0。⑤ “用仓库机密发布就行” —— 优先使用带必需审阅者的环境机密;来自分叉仓库的拉取请求工作流本来就拿不到机密。

图解:OpsKit 发布流水线

git pushPR · main · 标签 v1.0.0 作业:test(矩阵) windows ubuntu macos checkout · shell: pwsh Install-PSResource Pester 6.2.0、PSSA 1.25.0 ./build.ps1 -Task Analyze ./build.ps1 -Task Test(失败时 exit 1) upload-artifact(if: always()) testResults.xml · coverage.xml needs 作业:publish(仅 refs/tags/v*) environment: psgallery(需批准) 标签 == v + ModuleVersion [+ -Prerelease]? ./build.ps1 -Task Package Publish-PSResource -ApiKey $env:PSGALLERY_API_KEY secrets.PSGALLERY_API_KEY(环境机密) PowerShell GalleryOpsKit 1.0.0
图 7-1:测试守住一切;只有在三个操作系统上都通过的提交上打的标签才能进入发布作业

发布流水线:这个事件会运行什么?

就绪。
动画背后的真实机制 GitHub Actions 根据 on: 过滤器决定是否运行工作流,把矩阵展开成并行作业,只有当所有 needs 作业成功且其 if: 表达式为真时才运行 publish。使用 shell: pwsh 时,每个 run: 块被保存为临时 .ps1 并由 pwsh 执行;非零的 $LASTEXITCODE 或终止性错误会让该步骤失败。

命令表

命令用途说明
Get-AuthenticodeSignature ./x.ps1签名状态与签名者只读;适用于任何支持 Authenticode 的文件类型
Set-AuthenticodeSignature -FilePath x.ps1 -Certificate $cert -TimestampServer http://timestamp.digicert.com签名需要代码签名证书;加时间戳,让签名在证书过期后仍有效
Get-ExecutionPolicy -List各作用域的生效策略第 1 课
$ExecutionContext.SessionState.LanguageModeFullLanguage / ConstrainedLanguage在会话中改为 Constrained 是单向的
[semver]'1.0.0-rc.1'解析/比较 SemVer 2.0.PreReleaseLabel、.BuildLabel
Update-PSModuleManifest -ModuleVersion 1.0.0 -Prerelease rc1编辑清单属于 PSResourceGet;会重写整个文件
Test-ModuleManifest ./OpsKit.psd1校验并读取清单清单损坏时抛错
Publish-PSResource -Path dir -Repository PSGallery -ApiKey $key发布-DestinationPath 还可保存 .nupkg

1. 签名、策略与受限语言(只读)

Get-AuthenticodeSignature -FilePath ./OpsKit/OpsKit.psm1 | Format-List Status, StatusMessage, SignerCertificate
$psrg = (Get-Module Microsoft.PowerShell.PSResourceGet -ListAvailable | Select-Object -First 1).Path
Get-AuthenticodeSignature -FilePath $psrg |
    Select-Object Status, SignatureType, @{ n = 'Signer'; e = { $_.SignerCertificate.Subject -replace ',.*' } }, @{ n = 'File'; e = { Split-Path $_.Path -Leaf } } | Format-List
Get-ExecutionPolicy -List | Format-Table -AutoSize
'--- constrained language (this process only)'
$ExecutionContext.SessionState.LanguageMode
$ExecutionContext.SessionState.LanguageMode = 'ConstrainedLanguage'
$ExecutionContext.SessionState.LanguageMode
Get-Date -Format yyyy | Out-Null; 'cmdlets still work'
[System.IO.File]::ReadAllText("$PWD/data/servers.csv").Length
try { Add-Type -TypeDefinition 'public class X {}' } catch { $_.Exception.Message }
[pscustomobject]@{ Ok = $true }
Status            : NotSigned
StatusMessage     : The file C:\Users\labadmin\pslab\OpsKit\OpsKit.psm1 is not digitally signed. You cannot run this
                    script on the current system. For more information about running scripts and setting execution
                    policy, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170
SignerCertificate : 


Status        : Valid
SignatureType : Authenticode
Signer        : CN=Microsoft Corporation
File          : Microsoft.PowerShell.PSResourceGet.psd1


        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser          Bypass
 LocalMachine    RemoteSigned

--- constrained language (this process only)
FullLanguage
ConstrainedLanguage
cmdlets still work
InvalidOperation: C:\Users\labadmin\pslab\lab\s1.ps1:11
Line |
  11 |  [System.IO.File]::ReadAllText("$PWD/data/servers.csv").Length
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot invoke method. Method invocation is supported only on core types in this language mode.
Cannot add type. Definition of new types is not supported in this language mode.
InvalidArgument: C:\Users\labadmin\pslab\lab\s1.ps1:13
Line |
  13 |  [pscustomobject]@{ Ok = $true }
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot convert value to type "System.Management.Automation.LanguagePrimitives+InternalPSCustomObject". Only core
     | types are supported in this language mode.

如何验证:OpsKit 是 NotSigned;Microsoft 的 PSResourceGet 清单是 Valid。“You cannot run this script” 只是通用的状态说明 —— 在 RemoteSigned 下本地文件仍然可以运行。把进程切换到 ConstrainedLanguage 后,cmdlet 正常工作,但 .NET 方法调用、Add-Type 甚至 [pscustomobject] 都被阻止。

2. 签名(预期输出 —— 未运行,因为它会在用户证书存储中创建证书)

# 仅限实验:自签名代码签名证书(生产环境请使用组织的 CA)
$cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject 'CN=OpsKit Dev' -CertStoreLocation Cert:\CurrentUser\My
Get-ChildItem ./OpsKit -Include *.ps1, *.psm1, *.psd1 -Recurse |
    Set-AuthenticodeSignature -Certificate $cert -TimestampServer 'http://timestamp.digicert.com' |
    Format-Table Status, @{ n = 'File'; e = { Split-Path $_.Path -Leaf } }
Get-AuthenticodeSignature ./OpsKit/OpsKit.psm1 | Format-List Status, StatusMessage
Status File
------ ----
 Valid Get-OpsConfig.ps1
 …
 Valid OpsKit.psm1

Status        : UnknownError
StatusMessage : A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.

刚签名后 Set-AuthenticodeSignature 报告 Valid,但验证时会显示自签名根证书不受信任,除非把证书放入受信任的根和受信任的发布者 —— 这正是实验证书绝不能在整台机器上被信任的原因。签名后再编辑文件会改变其哈希:状态变为 HashMismatch,在 AllSigned 下不再能运行。在最后一次修改之后签名,作为构建的最后一步。

3. SemVer 与清单

[semver]'1.0.0-rc1' -lt [semver]'1.0.0'
[semver]'1.0.0-rc.2' -lt [semver]'1.0.0-rc.10'
[semver]'1.0.0-rc2' -lt [semver]'1.0.0-rc10'
[version]'1.10.0' -gt [version]'1.9.0'
'1.10.0' -gt '1.9.0'
try { [version]'1.0.0-rc1' } catch { $_.Exception.InnerException.Message }
$v = [semver]'1.2.3-rc.1+build.45'
$v | Format-List Major, Minor, Patch, PreReleaseLabel, BuildLabel
'--- manifest'
Copy-Item ./OpsKit/OpsKit.psd1 ./tmp-OpsKit.psd1
Copy-Item ./OpsKit/OpsKit.psm1 ./tmp-OpsKit.psm1
(Get-Content ./tmp-OpsKit.psd1) -replace 'OpsKit.psm1', 'tmp-OpsKit.psm1' | Set-Content ./tmp-OpsKit.psd1
Update-PSModuleManifest -Path ./tmp-OpsKit.psd1 -ModuleVersion '1.0.0' -Prerelease 'rc1'
$m = Test-ModuleManifest ./tmp-OpsKit.psd1
"Version=$($m.Version) Prerelease=$($m.PrivateData.PSData.Prerelease)"
Select-String -Path ./tmp-OpsKit.psd1 -Pattern 'ModuleVersion|Prerelease' | ForEach-Object { $_.Line.Trim() }
try { Update-PSModuleManifest -Path ./tmp-OpsKit.psd1 -ModuleVersion '1.0.0-rc1' } catch { "error: $($_.Exception.Message)" }
Remove-Item ./tmp-OpsKit.psd1, ./tmp-OpsKit.psm1
True
True
False
True
False
Cannot convert value "1.0.0-rc1" to type "System.Version". Error: "The input string '0-rc1' was not in a correct format."

Major           : 1
Minor           : 2
Patch           : 3
PreReleaseLabel : rc.1
BuildLabel      : build.45

--- manifest
Version=1.0.0 Prerelease=rc1
ModuleVersion = '1.0.0'
# Prerelease string of this module
Prerelease = 'rc1'
error: Cannot bind parameter 'ModuleVersion'. Cannot convert value "1.0.0-rc1" to type "System.Version". Error: "The input string '0-rc1' was not in a correct format."

4. CHANGELOG.md

# Changelog

All notable changes to OpsKit are documented here.
The format follows Keep a Changelog, and OpsKit uses Semantic Versioning.

## [1.0.0] - 2026-11-24
### Added
- Pester 6 test suite (48 tests) with code coverage and NUnit test results.
- PSScriptAnalyzer settings and a clean analysis of every module file.
- build.ps1 with Analyze, Test and Package tasks; GitHub Actions workflow.
### Changed
- Test-OpsEndpoint returns StatusCode 0 and an Error message instead of throwing on network errors.
- Invoke-OpsHealthCheck accepts -Environment to check a subset.
### Fixed
- Get-OpsServer returns Role as an array, so "web,api" matches -Role api.

## [0.5.0] - Lesson 7
### Added
- Invoke-OpsApi (retries for 429 and 5xx) and Get-OpsCloudInventory.

## [0.4.0] - Lesson 6
### Added
- Invoke-OpsHealthCheck.

## [0.3.0] - Lesson 5
### Added
- Invoke-OpsBackup with rotation, -WhatIf and a JSON log.

5. .github/workflows/opskit.yml

name: OpsKit CI

on:
  push:
    branches: [main]
    tags: ['v*.*.*']
  pull_request:
    branches: [main]

permissions:
  contents: read

jobs:
  test:
    name: Test (${{ matrix.os }})
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [windows-latest, ubuntu-latest, macos-latest]
    defaults:
      run:
        shell: pwsh
    steps:
      - uses: actions/checkout@v7

      - name: Show PowerShell version
        run: $PSVersionTable | Format-Table -AutoSize

      - name: Install pinned Pester and PSScriptAnalyzer
        run: |
          Set-PSResourceRepository -Name PSGallery -Trusted
          Install-PSResource -Name Pester -Version 6.2.0 -Scope CurrentUser
          Install-PSResource -Name PSScriptAnalyzer -Version 1.25.0 -Scope CurrentUser
          Get-Module Pester, PSScriptAnalyzer -ListAvailable | Format-Table Name, Version

      - name: Analyze
        run: ./build.ps1 -Task Analyze

      - name: Test
        run: ./build.ps1 -Task Test

      - name: Upload test results and coverage
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: test-results-${{ matrix.os }}
          path: |
            out/testResults.xml
            out/coverage.xml

  publish:
    name: Publish to PowerShell Gallery
    needs: test
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    environment: psgallery
    defaults:
      run:
        shell: pwsh
    steps:
      - uses: actions/checkout@v7

      - name: Check that the tag matches ModuleVersion
        run: |
          $manifest = Test-ModuleManifest ./OpsKit.psd1
          $version = "$($manifest.Version)"
          $pre = $manifest.PrivateData.PSData.Prerelease
          if ($pre) { $version = "$version-$pre" }
          if ("v$version" -ne $env:GITHUB_REF_NAME) {
            throw "Tag $env:GITHUB_REF_NAME does not match manifest version v$version"
          }

      - name: Package
        run: ./build.ps1 -Task Package

      - name: Publish
        env:
          PSGALLERY_API_KEY: ${{ secrets.PSGALLERY_API_KEY }}
        run: |
          Publish-PSResource -Path ./out/stage/OpsKit -Repository PSGallery -ApiKey $env:PSGALLERY_API_KEY

不运行 GitHub 即完成校验:用 powershell-yaml 模块解析,并把每个 run: 块当作 PowerShell 解析:

Import-Module ./yamlmod/powershell-yaml
$wf = Get-Content ./OpsKit/.github/workflows/opskit.yml -Raw | ConvertFrom-Yaml
"jobs: $($wf.jobs.Keys -join ', ')"
"matrix: $($wf.jobs.test.strategy.matrix.os -join ', ')"
"test steps: $($wf.jobs.test.steps.Count); publish needs: $($wf.jobs.publish.needs); publish if: $($wf.jobs.publish.if)"
"triggers: $($wf.on.Keys -join ', '); tags: $($wf.on.push.tags -join ', ')"
foreach ($job in $wf.jobs.Keys) {
    foreach ($step in $wf.jobs[$job].steps) {
        if (-not ($step.uses -or $step.run)) { throw "step without uses/run in $job" }
        if ($step.run) {
            $errs = $null
            $null = [System.Management.Automation.Language.Parser]::ParseInput(($step.run -replace '\$\{\{[^}]+\}\}', 'X'), [ref]$null, [ref]$errs)
            if ($errs) { "PARSE ERROR in $job/$($step.name): $($errs[0].Message)" }
        }
    }
}
'all run: blocks parse as PowerShell'
jobs: test, publish
matrix: windows-latest, ubuntu-latest, macos-latest
test steps: 6; publish needs: test; publish if: startsWith(github.ref, 'refs/tags/v')
triggers: pull_request, push; tags: v*.*.*
all run: blocks parse as PowerShell

如何验证:截至 2026-11-24,actions/checkout@v7 和 actions/upload-artifact@v7 是最新的主版本(GitHub API)。常见错误:上传步骤忘了 if: always() —— 结果恰恰在测试失败时消失。生产用法:把第三方 Action 固定到完整的提交 SHA,保持 permissions: contents: read,并把 API 密钥放在受保护的环境中。本课没有实际执行该工作流。

目标:准备 OpsKit 的发布元数据和 CI 工作流。环境:pwsh 7.6、OpsKit 目录。费用:无(不推送任何内容)。

检查本机上的签名和语言模式:Get-ChildItem ./OpsKit -Recurse -Include *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Group-Object Status -NoElement 以及 $ExecutionContext.SessionState.LanguageMode。
在一次性进程中试用 CLM:
pwsh -NoProfile -Command '$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"; Import-Module ./OpsKit/OpsKit.psd1; Get-OpsServer -Path ./data/servers.csv | Select-Object -First 1'
InvalidOperation: C:\Users\labadmin\pslab\OpsKit\Private\Resolve-OpsPath.ps1:15
Line |
  15 |      $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFrom …
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot invoke method. Method invocation is supported only on core types in this language mode.
Import-Csv: C:\Users\labadmin\pslab\OpsKit\Public\Get-OpsServer.ps1:19
Line |
  19 |      $rows = Import-Csv -LiteralPath (Resolve-OpsPath -Path $Path)
     |                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot validate argument on parameter 'LiteralPath'. The argument is null or empty. …

第一个失败是私有辅助函数中的 .NET 方法调用,第二个错误是它的后果 —— 典型的 CLM 失败链。在 CLM 机器上,OpsKit 需要经过签名并被策略允许。

编写 CHANGELOG.md,为 1.0.0 写 Added / Changed / Fixed 三节(见“命令”页)。
编写工作流到 ./OpsKit/.github/workflows/opskit.yml,然后校验:Install-PSResource powershell-yaml -Scope CurrentUser(或 Save-PSResource),再运行“命令”页中的校验脚本。
比较版本:先预测,再检查 [semver]'1.0.0-rc.9' -lt [semver]'1.0.0-rc.10' 和 [semver]'1.0.0-rc9' -lt [semver]'1.0.0-rc10'。
清理:无需清理;工作流文件留给模块 8 使用。

案例 1:一次热修复让所有 AllSigned 服务器都无法运行

问题:对一个已签名模块做了一行热修复后,所有服务器都报告 “is not digitally signed”。根因:工程师直接在服务器上编辑了文件;哈希不再匹配(HashMismatch)。修复:修复一律走流水线,签名是构建的最后一步,服务器只接收打好的包。

案例 2:装上的是 1.0.0-rc9 而不是 rc10

问题:用户请求“最新预发布版”,拿到的是 rc9,尽管 rc10 已经存在。根因:标签 rc9/rc10 按字符串比较(rc10 < rc9)。修复:使用 rc01…rc10,或在工具支持时使用点分的 rc.9/rc.10,并在打标签前用 [semver] 测试。

案例 3:API 密钥泄露到日志中

问题:某个步骤执行了 Write-Host "Publishing with key $key"。GitHub 会在日志中屏蔽已注册的机密,但变换过的值(例如 Base64)不会被屏蔽。修复:绝不打印机密;通过 env: 只传给需要它的那一个命令;一有怀疑就轮换。

常见错误与修复

File … cannot be loaded. The file … is not digitally signed.

原因:AllSigned(或 RemoteSigned 且文件带有 Zone.Identifier 标记)。修复:在构建中签名;对下载的文件在审阅后使用 Unblock-File。

Get-AuthenticodeSignature:HashMismatch

原因:文件在签名后被修改(包括 Git 转换了换行符:在 .gitattributes 中为已签名文件设置 *.ps1 -text 或 eol=crlf)。

Cannot convert value "1.0.0-rc1" to type "System.Version"

原因:ModuleVersion 中带了标签。修复:ModuleVersion = '1.0.0' 加 Prerelease = 'rc1'。

Update-PSModuleManifest: Cannot validate argument on parameter 'Prerelease'. The argument is null or empty.

原因:已在 PSResourceGet 1.2.1 上验证:清单中有 Prerelease = ''。修复:删除空的 Prerelease 行(模块 8)。

工作流:“Invalid workflow file … mapping values are not allowed here”

原因:YAML 缩进错误,或未加引号的值中含有 : 。修复:在本地校验(“命令”页第 5 步),给表达式加引号,并保持 run: | 块缩进一致。

命令行练习
1. 列出 OpsKit 中所有签名无效的文件。
Get-ChildItem ./OpsKit -Recurse -Include *.ps1, *.psm1, *.psd1 | Get-AuthenticodeSignature |
    Where-Object Status -ne 'Valid' | Select-Object Status, Path
2. 从清单计算完整的版本字符串(含预发布标签)。
$m = Test-ModuleManifest ./OpsKit/OpsKit.psd1
$v = "$($m.Version)"; if ($m.PrivateData.PSData.Prerelease) { $v += "-$($m.PrivateData.PSData.Prerelease)" }
$v
场景分析
安全团队要求你让 OpsKit 在一批同时启用 App Control 的服务器上“满足 AllSigned”。你的计划是什么?

① 从内部 CA 获取代码签名证书(对外部用户则用公共 CA),存放在只有发布作业能访问的安全签名服务或 HSM 中。② 在 Package 的暂存步骤之后加一个 Sign 任务:为每个 .ps1/.psm1/.psd1 签名并加时间戳,然后再打包。③ 确保 Git 不会改变已签名文件的换行符。④ 请 App Control 负责人允许该发布者证书,让 OpsKit 运行在 FullLanguage 中。⑤ 增加一个测试:任何暂存文件不是 Valid 时失败。⑥ 只通过内部仓库分发。

已验证的教学视频

▶
Streamline Module Publishing to PowerShell Gallery Using GitHub Actions — Jeff Brown Tech
英文 · 在工作流中测试并发布
▶
GitHub Actions for Fun and Profit by Adam Driscoll — PowerShell.org
英文 · 在 GitHub Actions 中使用 PowerShell

没有找到讲解 Authenticode 签名或受限语言模式的已验证视频;请参考下面的文档。

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–25 秒
画面:一个盖着火漆印章(签名)的脚本;一个字符被改动,印章裂开(HashMismatch)。
旁白:签名证明是谁签的、内容未改 —— 最后再签名。
镜头 2 · 25–50 秒
画面:一台锁定的机器;未签名模块中的 [pscustomobject] 行闪红。
旁白:在启用 App Control 的机器上,不可信代码运行在受限语言模式中。
镜头 3 · 50–90 秒
画面:三个操作系统的矩阵依次变绿,然后标签 v1.0.0 打开了发布闸门。
旁白:处处都测试,只从与清单一致的标签发布。
或测验得分 ≥ 70%

模块 8 · OpsKit v1.0:测试、分析、CI 与发布

50:00 – 60:00 · 把一切组合起来:100% 命令覆盖率的完整测试套件、零告警的分析结果、1.0.0 版本、一个包含 Analyze / Test / Package 任务且 CI 与人用法完全相同的 build.ps1,以及本地文件夹仓库中的 .nupkg
10 分钟build.ps1 · Compress-PSResource★★★★★
学习目标
  • 按公有函数组织测试,并加上模块级测试(清单、导出、帮助),达到 80% 覆盖率阈值 —— OpsKit 达到 100%。
  • 用项目配置文件和 Invoke-Formatter 让分析结果清零。
  • 用 Update-PSModuleManifest 升级到 1.0.0,并处理它在 Prerelease = '' 上的失败。
  • 编写 build.ps1:快速失败(exit 1)、强制覆盖率、只暂存模块文件,并用 Compress-PSResource 生成 OpsKit.1.0.0.nupkg;发布到文件夹仓库。
前置条件:模块 2–7;第 4 课(仓库)。重要度:★★★★★(这就是里程碑)

是什么:v1.0 的完成标准

门禁阈值OpsKit 1.0.0 结果(已验证)
单元测试在 Windows、Ubuntu、macOS 上全部通过51 个通过,0 个失败(Windows 上运行;其他系统由工作流负责)
Public + Private 覆盖率≥ 80%(由 build.ps1 强制)100% —— 9 个文件中 167/167 条命令
PSScriptAnalyzer使用项目配置时 0 个 Error、0 个 Warning0 条(修复了 3 条花括号位置告警之后)
清单ModuleVersion = '1.0.0'、有效、导出 = Public/*.ps1Test-ModuleManifest:1.0.0,7 个函数
包只包含模块文件的 .nupkgOpsKit.1.0.0.nupkg,10,808 字节,12 个文件 + nuspec
文档每个公有函数都有带示例的帮助;CHANGELOG由 OpsKit.Module.Tests.ps1 强制

为什么:人与 CI 共用一个构建脚本

如果 CI 运行的命令开发者从不运行,“本地正常、CI 失败”就在所难免。build.ps1 是唯一入口:开发者推送前运行 ./build.ps1,工作流调用 ./build.ps1 -Task Analyze 和 -Task Test。它设置 $ErrorActionPreference = 'Stop' 和 Set-StrictMode -Version Latest,把任务包在 try/catch 中,把任何失败转换为 exit 1(第 1 课:用 pwsh -File 运行)。

怎么做:测试的组织方式

文件测试数技术
Get-OpsServer.Tests.ps19TestDrive 测试数据、-ForEach、Should-All、经典 Should
Get-OpsConfig.Tests.ps16Should-BeEquivalent、Should-Throw -ExceptionType/-ExceptionMessage
Invoke-OpsBackup.Tests.ps17BeforeEach 隔离、Mock Get-Date、-WhatIf、Should-Invoke Remove-Item
Test-OpsEndpoint.Tests.ps15Invoke-WebRequest 的默认 Mock + 过滤 Mock、管道输入
Invoke-OpsApi.Tests.ps16重试序列、HttpResponseException、Mock Start-Sleep、Should-NotInvoke
Invoke-OpsHealthCheck.Tests.ps13Mock 模块内部使用的公有函数、TestDrive 中的日志文件
Get-OpsCloudInventory.Tests.ps12为未安装的命令建桩、Mock Get-Command
Private.Tests.ps14InModuleScope -Parameters
OpsKit.Module.Tests.ps19清单、导出 = Public 目录、每个函数的帮助(发现阶段的 -ForEach)

何时用:按顺序的发布步骤

① 测试全绿且覆盖率 ≥ 80% → ② 分析清零 → ③ 写 CHANGELOG 条目 → ④ Update-PSModuleManifest -ModuleVersion 1.0.0 → ⑤ ./build.ps1 → ⑥ 从文件夹仓库安装 .nupkg 并做冒烟测试 → ⑦ 提交、打标签 v1.0.0、推送 → 工作流发布(模块 7)。

常见误区① “覆盖率 100%,构建不会漏掉缺陷” —— 破坏 Monitored 解析后,51 个测试中只有 1 个失败,而且只是因为 Should-All 拒绝空集合(在“命令”页复现)。② “直接打包项目目录就行” —— 会把测试、构建脚本和 out/ 都发出去;只暂存模块文件。③ “Update-PSModuleManifest 只改版本号” —— 它会重新生成整个文件(注释、布局),并且在 1.2.1 中遇到空的 Prerelease 会失败。④ “VS Code 里分析通过了,CI 也会通过” —— CI 使用项目配置文件,花括号规则更严格;请在本地运行 ./build.ps1 -Task Analyze。⑤ “文件夹仓库需要服务器” —— 它就是一个放 .nupkg 的文件夹。

图解:build.ps1

./build.ps1-Task All-CoverageThreshold 80 AnalyzeInvoke-ScriptAnalyzer-Settings 项目配置psm1 + Public + Private有任何告警 → throw TestPester 6 配置coverage.xml · testResults.xmlFailedCount > 0 → throw覆盖率 < 阈值 → throw PackageTest-ModuleManifest暂存 psd1 psm1 Public Private CHANGELOGCompress-PSResource → out/repoOpsKit.1.0.0.nupkg catch → “Build failed: …” → exit 1 · 成功 → “Build succeeded.” → exit 0
图 8-1:每个任务失败时都会抛出异常;一个 catch 把任何失败都转换为 CI 能识别的退出码 1

build.ps1 守门人

日志是为本课录制的真实运行输出。

就绪。
动画背后的真实机制 每个任务函数要么完成、要么抛出异常;$ErrorActionPreference = 'Stop' 让其中的非终止性错误也变成异常。遍历任务名的 foreach 在第一个异常处停止,catch 打印一行原因并调用 exit 1,pwsh -File 再把它传给调用方(第 1 课)。

命令表

命令用途
./build.ps1 / -Task Analyze, Test运行全部或指定任务
Update-PSModuleManifest -Path ./OpsKit.psd1 -ModuleVersion 1.0.0升级版本
Compress-PSResource -Path ./out/stage/OpsKit -DestinationPath ./out/repo生成 .nupkg 而不发布
Register-PSResourceRepository -Name OpsKitLocal -Uri ~/pslab/OpsKit/out/repo -Trusted文件夹仓库(第 4 课)
Install-PSResource OpsKit -Version 1.0.0 -Repository OpsKitLocal -Scope CurrentUser对包做冒烟测试

1. 之前:OpsKit v0.5 的覆盖率

Import-Module Pester -MinimumVersion 6.0.0
Set-Location ./OpsKit
$config = New-PesterConfiguration
$config.Run.Path = './tests/Get-OpsServer.Tests.ps1', './tests/Get-OpsConfig.Tests.ps1'
$config.Run.Exit = $true
$config.Output.Verbosity = 'Normal'
$config.CodeCoverage.Enabled = $true
$config.CodeCoverage.Path = './Public', './Private'
$config.CodeCoverage.OutputPath = './out/coverage-partial.xml'
$config.CodeCoverage.CoveragePercentTarget = 80
Invoke-Pester -Configuration $config
Running tests from 2 files.
Starting code coverage.
[+] C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsServer.Tests.ps1 1.07s (9 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsConfig.Tests.ps1 347ms (6 tests)
Tests completed in 1.44s
Tests Passed: 15, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0
Processing code coverage result.
Covered 29.34% / 80%. 167 analyzed Commands in 9 Files.

2. 全部测试

Import-Module Pester -MinimumVersion 6.0.0
Invoke-Pester -Path ./OpsKit/tests -Output Detailed
Pester v6.2.0

Running tests from 9 files.

Running tests from 'C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsCloudInventory.Tests.ps1'
Describing Get-OpsCloudInventory
  [+] flattens Azure resources and reads the env tag 447ms
  [+] explains what is missing when Az.Resources is not available 145ms

Running tests from 'C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsConfig.Tests.ps1'
Describing Get-OpsConfig
  [+] returns the whole configuration as a hashtable 30ms
  [+] returns one environment as an object 115ms
  [+] defaults RequireConfirm to $false 8ms
  [+] names the known environments when the environment is unknown 12ms
  [+] throws FileNotFoundException for a missing file 12ms
  [+] rejects a file without the required keys 9ms

Running tests from 'C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsServer.Tests.ps1'
Describing Get-OpsServer
 Context without filters
   [+] returns one object per CSV row 9ms
   [+] converts Monitored to a real boolean 9ms
   [+] splits a quoted multi-role value into an array 27ms
   [+] still supports the classic Should syntax 59ms
 Context with filters
   [+] filters by environment dev: 2 servers 49ms
   [+] filters by environment prod: 3 servers 4ms
   [+] filters by role, including multi-role servers 5ms
   [+] returns only monitored servers with -MonitoredOnly 18ms
   [+] rejects an unknown environment 8ms

Running tests from 'C:\Users\labadmin\pslab\OpsKit\tests\Invoke-OpsApi.Tests.ps1'
Describing Invoke-OpsApi
  [+] returns the parsed response 104ms
  [+] retries a 503 and then succeeds 168ms
  [+] does not retry a 404 66ms
  [+] gives up after MaxRetries 106ms
  [+] sends a body as compressed JSON 85ms
What if: Performing the operation "HTTP Post" on target "http://127.0.0.1:8088/api/tags".
  [+] makes no call for a POST with -WhatIf 31ms

Running tests from 'C:\Users\labadmin\pslab\OpsKit\tests\Invoke-OpsBackup.Tests.ps1'
Describing Invoke-OpsBackup
  [+] creates one zip named after the timestamp 102ms
  [+] keeps relative paths, odd names included, and skips excluded files 54ms
What if: Performing the operation "Create backup of 3 file(s) from C:\Users\labadmin\AppData\Local\Temp\Pester_jzxf\src-f9080a25-adc9-4cdd-8cde-84aeee0eb04b" on target "C:\Users\labadmin\AppData\Local\Temp\Pester_jzxf\dst-65410d59-50ae-4305-ac95-2ae0bc4ef1fe\backup-20261124-101500.zip".
  [+] changes nothing with -WhatIf 36ms
  [+] keeps only the newest 2 backups 59ms
  [+] keeps only the newest 3 backups 40ms
  [+] asks ShouldProcess before removing an expired backup 79ms
  [+] fails clearly when the source folder does not exist 30ms

Running tests from 'C:\Users\labadmin\pslab\OpsKit\tests\Invoke-OpsHealthCheck.Tests.ps1'
Describing Invoke-OpsHealthCheck
  [+] checks every environment in sorted order 47ms
  [+] uses the timeout from the configuration 24ms
  [+] logs a warning line for an unhealthy environment 68ms

Running tests from 'C:\Users\labadmin\pslab\OpsKit\tests\OpsKit.Module.Tests.ps1'
Describing OpsKit module
  [+] has a valid manifest with a SemVer version 10ms
  [+] exports exactly the functions in Public/ 10ms
  [+] Get-OpsCloudInventory has comment-based help with an example 31ms
  [+] Get-OpsConfig has comment-based help with an example 8ms
  [+] Get-OpsServer has comment-based help with an example 9ms
  [+] Invoke-OpsApi has comment-based help with an example 9ms
  [+] Invoke-OpsBackup has comment-based help with an example 9ms
  [+] Invoke-OpsHealthCheck has comment-based help with an example 9ms
  [+] Test-OpsEndpoint has comment-based help with an example 10ms

Running tests from 'C:\Users\labadmin\pslab\OpsKit\tests\Private.Tests.ps1'
Describing Private helpers
  [+] are not exported 14ms
  [+] Resolve-OpsPath expands ~ 20ms
  [+] Resolve-OpsPath expands ~/pslab/data 6ms
  [+] Write-OpsLog writes one JSON line per entry 22ms

Running tests from 'C:\Users\labadmin\pslab\OpsKit\tests\Test-OpsEndpoint.Tests.ps1'
Describing Test-OpsEndpoint
  [+] reports a 200 as healthy 53ms
  [+] reports a 503 as unhealthy 28ms
  [+] turns a network error into StatusCode 0 instead of throwing 34ms
  [+] passes the timeout through to Invoke-WebRequest 31ms
  [+] accepts HealthUrl from the pipeline by property name 28ms
Tests completed in 5.1s
Tests Passed: 51, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0

3. 项目分析配置,以及第一次 Analyze 运行

@{
    Severity     = @('Error', 'Warning')
    IncludeDefaultRules = $true
    Rules        = @{
        PSUseCompatibleSyntax      = @{
            Enable         = $true
            TargetVersions = @('7.4')
        }
        PSPlaceOpenBrace           = @{ Enable = $true; OnSameLine = $true; NewLineAfter = $true }
        PSPlaceCloseBrace          = @{ Enable = $true; NewLineAfter = $false }
        PSUseConsistentIndentation = @{ Enable = $true; IndentationSize = 4; Kind = 'space' }
        PSUseCorrectCasing         = @{ Enable = $true }
    }
}
==> Analyze

Severity RuleName          ScriptName           Line
-------- --------          ----------           ----
 Warning PSPlaceCloseBrace Invoke-OpsApi.ps1      39
 Warning PSPlaceCloseBrace Invoke-OpsBackup.ps1   41
 Warning PSPlaceCloseBrace Test-OpsEndpoint.ps1   23


Build failed: Analyze: 3 finding(s).
exit=1
Set-Location ./OpsKit
Import-Module PSScriptAnalyzer
foreach ($file in Get-ChildItem ./Public, ./Private -Filter *.ps1) {
    $before = Get-Content -LiteralPath $file.FullName -Raw
    $after = Invoke-Formatter -ScriptDefinition $before -Settings ./PSScriptAnalyzerSettings.psd1
    if ($after -ne $before) {
        Set-Content -LiteralPath $file.FullName -Value $after -NoNewline
        "reformatted $($file.Name)"
    }
}
./build.ps1 -Task Analyze
"exit=$LASTEXITCODE"
reformatted Invoke-OpsApi.ps1
reformatted Invoke-OpsBackup.ps1
reformatted Test-OpsEndpoint.ps1
==> Analyze
Analyze: 0 findings.
Build succeeded.
exit=0

配置要求 } catch { 写在同一行(PSPlaceCloseBrace NewLineAfter = $false);使用同一配置的 Invoke-Formatter 重写了这三个文件。

4. 1.0.0 版本 —— 以及一个 Update-PSModuleManifest 缺陷

@{
    RootModule        = 'OpsKit.psm1'
    ModuleVersion     = '0.5.0'
    GUID              = '6f1d2c3e-8b4a-4e57-9a0c-2d7e5b1f9c42'
    Author            = 'pslab'
    CompanyName       = 'pslab'
    Copyright         = '(c) 2026 pslab. MIT License.'
    Description       = 'OpsKit: inventory, configuration, endpoint checks, backups and API helpers (PowerShell course project).'
    PowerShellVersion = '7.4'
    FunctionsToExport = @('Get-OpsCloudInventory', 'Get-OpsConfig', 'Get-OpsServer', 'Invoke-OpsApi', 'Invoke-OpsBackup', 'Invoke-OpsHealthCheck', 'Test-OpsEndpoint')
    CmdletsToExport   = @()
    VariablesToExport = @()
    AliasesToExport   = @()
    PrivateData       = @{
        PSData = @{
            Tags         = @('ops', 'inventory', 'backup', 'course')
            LicenseUri   = 'https://opensource.org/licenses/MIT'
            ProjectUri   = 'https://github.com/example/OpsKit'
            ReleaseNotes = 'See CHANGELOG.md'
            Prerelease   = ''
        }
    }
}
Set-Location ./OpsKit
Update-PSModuleManifest -Path ./OpsKit.psd1 -ModuleVersion '1.0.0' -ReleaseNotes 'See CHANGELOG.md: 1.0.0'
Update-PSModuleManifest: C:\Users\labadmin\pslab\lab\b3.ps1:2
Line |
   2 |  Update-PSModuleManifest -Path ./OpsKit.psd1 -ModuleVersion '1.0.0' -R …
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Error occurred while running 'New-ModuleManifest': Cannot validate argument on parameter 'Prerelease'. The
     | argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

v0.5 的清单中有 Prerelease = ''。删除这一行后再次升级:

Set-Location ./OpsKit
Update-PSModuleManifest -Path ./OpsKit.psd1 -ModuleVersion '1.0.0' -ReleaseNotes 'See CHANGELOG.md: 1.0.0'
(Test-ModuleManifest ./OpsKit.psd1) | Select-Object Name, Version, @{ n = 'Exported'; e = { $_.ExportedFunctions.Count } } | Format-Table -AutoSize
Name   Version Exported
----   ------- --------
OpsKit 1.0.0          7
@{
RootModule = 'OpsKit.psm1'
ModuleVersion = '1.0.0'
GUID = '6f1d2c3e-8b4a-4e57-9a0c-2d7e5b1f9c42'
Author = 'pslab'
CompanyName = 'pslab'
Copyright = '(c) 2026 pslab. MIT License.'
Description = 'OpsKit: inventory, configuration, endpoint checks, backups and API helpers (PowerShell course project).'
PowerShellVersion = '7.4'
FunctionsToExport = 'Get-OpsCloudInventory', 'Get-OpsConfig', 'Get-OpsServer', 
               'Invoke-OpsApi', 'Invoke-OpsBackup', 'Invoke-OpsHealthCheck', 
               'Test-OpsEndpoint'
CmdletsToExport = @()
AliasesToExport = @()
PrivateData = @{
    PSData = @{
        Tags = 'ops', 'inventory', 'backup', 'course'
        LicenseUri = 'https://opensource.org/licenses/MIT'
        ProjectUri = 'https://github.com/example/OpsKit'
        ReleaseNotes = 'See CHANGELOG.md: 1.0.0'
    } # End of PSData hashtable
} # End of PrivateData hashtable
}

上面的新清单省略了 Update-PSModuleManifest 生成的约 110 行注释。注意 VariablesToExport 变成了注释;提交前请检查 diff。

5. build.ps1

<#
.SYNOPSIS
    Builds OpsKit: Analyze, Test and Package.
.DESCRIPTION
    Analyze  PSScriptAnalyzer with PSScriptAnalyzerSettings.psd1; any Error or Warning fails the build.
    Test     Pester 6 with code coverage (JaCoCo) and test results (NUnitXml) in ./out.
    Package  Stages the module and creates ./out/repo/OpsKit.<version>.nupkg with Compress-PSResource.
    Exit codes: 0 success, 1 a task failed.
.EXAMPLE
    ./build.ps1
    ./build.ps1 -Task Test -CoverageThreshold 90
#>
#Requires -Version 7.4
[CmdletBinding()]
param(
    [ValidateSet('Analyze', 'Test', 'Package', 'All')]
    [string[]]$Task = 'All',

    [ValidateRange(0, 100)]
    [int]$CoverageThreshold = 80
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest

$root = $PSScriptRoot
$out = Join-Path $root 'out'
if ($Task -contains 'All') { $Task = 'Analyze', 'Test', 'Package' }

function Invoke-AnalyzeTask {
    Import-Module PSScriptAnalyzer -MinimumVersion 1.25.0
    $settings = Join-Path $root 'PSScriptAnalyzerSettings.psd1'
    $findings = @(
        foreach ($item in 'OpsKit.psm1', 'Public', 'Private') {
            Invoke-ScriptAnalyzer -Path (Join-Path $root $item) -Recurse -Settings $settings
        }
    )
    if ($findings.Count -gt 0) {
        $findings | Format-Table Severity, RuleName, ScriptName, Line -AutoSize | Out-String | Write-Host
        throw "Analyze: $($findings.Count) finding(s)."
    }
    Write-Host 'Analyze: 0 findings.'
}

function Invoke-TestTask {
    Import-Module Pester -MinimumVersion 6.0.0
    $config = New-PesterConfiguration
    $config.Run.Path = Join-Path $root 'tests'
    $config.Run.PassThru = $true
    $config.Output.Verbosity = 'Normal'
    $config.CodeCoverage.Enabled = $true
    $config.CodeCoverage.Path = (Join-Path $root 'Public'), (Join-Path $root 'Private')
    $config.CodeCoverage.OutputFormat = 'JaCoCo'
    $config.CodeCoverage.OutputPath = Join-Path $out 'coverage.xml'
    $config.CodeCoverage.CoveragePercentTarget = $CoverageThreshold
    $config.TestResult.Enabled = $true
    $config.TestResult.OutputFormat = 'NUnitXml'
    $config.TestResult.OutputPath = Join-Path $out 'testResults.xml'
    $result = Invoke-Pester -Configuration $config

    if ($result.FailedCount -gt 0) {
        throw "Test: $($result.FailedCount) test(s) failed."
    }
    $coverage = [math]::Round($result.CodeCoverage.CoveragePercent, 2)
    if ($coverage -lt $CoverageThreshold) {
        throw "Test: coverage $coverage% is below the $CoverageThreshold% threshold."
    }
    Write-Host "Test: $($result.PassedCount) passed, coverage $coverage% (threshold $CoverageThreshold%)."
}

function Invoke-PackageTask {
    $manifest = Test-ModuleManifest -Path (Join-Path $root 'OpsKit.psd1')
    $stage = Join-Path $out 'stage/OpsKit'
    $repo = Join-Path $out 'repo'
    Remove-Item -LiteralPath (Join-Path $out 'stage') -Recurse -Force -ErrorAction Ignore
    $null = New-Item -ItemType Directory -Path $stage, $repo -Force
    Copy-Item -Path (Join-Path $root '*') -Include 'OpsKit.psd1', 'OpsKit.psm1', 'CHANGELOG.md' -Destination $stage
    Copy-Item -Path (Join-Path $root 'Public'), (Join-Path $root 'Private') -Destination $stage -Recurse
    Compress-PSResource -Path $stage -DestinationPath $repo
    $nupkg = Join-Path $repo "OpsKit.$($manifest.Version).nupkg"
    if (-not (Test-Path -LiteralPath $nupkg)) {
        throw "Package: $nupkg was not created."
    }
    Write-Host "Package: $nupkg ($((Get-Item -LiteralPath $nupkg).Length) bytes)."
}

try {
    $null = New-Item -ItemType Directory -Path $out -Force
    foreach ($name in $Task) {
        Write-Host "==> $name" -ForegroundColor Cyan
        & "Invoke-${name}Task"
    }
    Write-Host 'Build succeeded.' -ForegroundColor Green
    exit 0
}
catch {
    Write-Host "Build failed: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}
Set-Location ./OpsKit
Remove-Item ./out -Recurse -Force -ErrorAction Ignore
pwsh -NoProfile -NonInteractive -File ./build.ps1
"exit=$LASTEXITCODE"
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip = [System.IO.Compression.ZipFile]::OpenRead((Resolve-Path ./out/repo/OpsKit.1.0.0.nupkg))
$zip.Entries.FullName | Where-Object { $_ -notmatch '^(_rels|package)/|\[Content_Types\]' } | Sort-Object
$zip.Dispose()
==> Analyze
Analyze: 0 findings.
==> Test

Running tests from 9 files.
Starting code coverage.
[+] C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsCloudInventory.Tests.ps1 1.26s (2 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsConfig.Tests.ps1 395ms (6 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Get-OpsServer.Tests.ps1 390ms (9 tests)
What if: Performing the operation "HTTP Post" on target "http://127.0.0.1:8088/api/tags".
[+] C:\Users\labadmin\pslab\OpsKit\tests\Invoke-OpsApi.Tests.ps1 613ms (6 tests)
What if: Performing the operation "Create backup of 3 file(s) from C:\Users\labadmin\AppData\Local\Temp\Pester_ftbj\src-927e2da1-0a46-4b43-acf9-403b4c1caee5" on target "C:\Users\labadmin\AppData\Local\Temp\Pester_ftbj\dst-f2a68b26-00ef-45f6-844b-b903f51107e5\backup-20261124-101500.zip".
[+] C:\Users\labadmin\pslab\OpsKit\tests\Invoke-OpsBackup.Tests.ps1 600ms (7 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Invoke-OpsHealthCheck.Tests.ps1 275ms (3 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\OpsKit.Module.Tests.ps1 390ms (9 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Private.Tests.ps1 183ms (4 tests)
[+] C:\Users\labadmin\pslab\OpsKit\tests\Test-OpsEndpoint.Tests.ps1 398ms (5 tests)
Tests completed in 4.55s
Tests Passed: 51, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0
Processing code coverage result.
Covered 100% / 80%. 167 analyzed Commands in 9 Files.
Test: 51 passed, coverage 100% (threshold 80%).
==> Package
Package: C:\Users\labadmin\pslab\OpsKit\out\repo\OpsKit.1.0.0.nupkg (10808 bytes).
Build succeeded.
exit=0
CHANGELOG.md
OpsKit.nuspec
OpsKit.psd1
OpsKit.psm1
Private/Resolve-OpsPath.ps1
Private/Write-OpsLog.ps1
Public/Get-OpsCloudInventory.ps1
Public/Get-OpsConfig.ps1
Public/Get-OpsServer.ps1
Public/Invoke-OpsApi.ps1
Public/Invoke-OpsBackup.ps1
Public/Invoke-OpsHealthCheck.ps1
Public/Test-OpsEndpoint.ps1

6. 构建抓住了一个真实缺陷

Set-Location ./OpsKit
$file = './Public/Get-OpsServer.ps1'
$original = Get-Content -LiteralPath $file -Raw
(Get-Content -LiteralPath $file -Raw).Replace("-eq 'true'", "-eq 'yes'") | Set-Content -LiteralPath $file -NoNewline
try {
    pwsh -NoProfile -NonInteractive -File ./build.ps1 -Task Test 2>&1 | Select-String -Pattern '\[-\]|Expected|Tests Passed|Build failed'
    "exit=$LASTEXITCODE"
} finally {
    Set-Content -LiteralPath $file -Value $original -NoNewline
}
[-] Get-OpsServer.with filters.returns only monitored servers with -MonitoredOnly 50ms
 Expected all items in collection to pass filter { $_.Monitored -eq $true }, but [Object[]] @() contains no items to 
compare.
Tests Passed: 50, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0
Build failed: Test: 1 test(s) failed.
exit=1

如何验证:当 Monitored 永远不为真时,“converts Monitored to a real boolean” 依然通过(它检查的是一个 false 行和类型),但 Get-OpsServer -MonitoredOnly | Should-All { … } 收到了空集合并失败。启示:除了检查返回结果的属性,还要对具体的期望值做断言(例如 @(Get-OpsServer -MonitoredOnly).Count | Should-Be 3)。

7. 发布到文件夹仓库并安装(预期输出 —— 未运行:会修改用户的仓库列表)

Register-PSResourceRepository -Name OpsKitLocal -Uri (Resolve-Path ~/pslab/OpsKit/out/repo).Path -Trusted
Find-PSResource -Name OpsKit -Repository OpsKitLocal
Install-PSResource -Name OpsKit -Version 1.0.0 -Repository OpsKitLocal -Scope CurrentUser
pwsh -NoProfile -Command 'Import-Module OpsKit; (Get-Module OpsKit).Version.ToString(); (Get-Command -Module OpsKit).Count'
Name   Version Prerelease Repository  Description
----   ------- ---------- ----------  -----------
OpsKit 1.0.0              OpsKitLocal OpsKit: inventory, configuration, endpoint checks, backups and API helpers …

1.0.0
7

另一种做法:Publish-PSResource -Path ./out/stage/OpsKit -Repository OpsKitLocal 也会把 .nupkg 写入该文件夹;Compress-PSResource 则无需注册任何仓库,这就是 build.ps1 采用它的原因。

8. 参考:OpsKit 1.0.0 源码

Get-OpsServer.ps1、Get-OpsConfig.ps1、Invoke-OpsBackup.ps1、Get-OpsCloudInventory.ps1、Private/*.ps1、OpsKit.Module.Tests.ps1
function Get-OpsServer {
    <#
    .SYNOPSIS
        Returns typed server objects from the inventory CSV.
    .EXAMPLE
        Get-OpsServer -Environment prod -Role web
    #>
    [CmdletBinding()]
    param(
        [string]$Path = (Join-Path $HOME 'pslab' 'data' 'servers.csv'),

        [ValidateSet('dev', 'staging', 'prod')]
        [string[]]$Environment,

        [string]$Role,

        [switch]$MonitoredOnly
    )
    $rows = Import-Csv -LiteralPath (Resolve-OpsPath -Path $Path)
    foreach ($row in $rows) {
        $server = [pscustomobject]@{
            PSTypeName = 'OpsKit.Server'
            Name       = $row.Name
            Env        = $row.Env
            Region     = $row.Region
            IP         = $row.IP
            Role       = @($row.Role -split ',')
            Monitored  = $row.Monitored -eq 'true'
        }
        if ($Environment -and $server.Env -notin $Environment) { continue }
        if ($Role -and $server.Role -notcontains $Role) { continue }
        if ($MonitoredOnly -and -not $server.Monitored) { continue }
        $server
    }
}
function Get-OpsConfig {
    <#
    .SYNOPSIS
        Reads the OpsKit configuration file (a .psd1 data file).
    .EXAMPLE
        Get-OpsConfig -Environment prod
    #>
    [CmdletBinding()]
    param(
        [string]$Path = (Join-Path $HOME 'pslab' 'data' 'opskit.config.psd1'),

        [string]$Environment
    )
    $fullPath = Resolve-OpsPath -Path $Path
    if (-not (Test-Path -LiteralPath $fullPath -PathType Leaf)) {
        throw [System.IO.FileNotFoundException]::new("OpsKit config not found: $fullPath", $fullPath)
    }
    $config = Import-PowerShellDataFile -LiteralPath $fullPath
    foreach ($key in 'DefaultEnv', 'Environments') {
        if (-not $config.ContainsKey($key)) {
            throw "OpsKit config '$fullPath' is missing the '$key' key."
        }
    }
    if (-not $Environment) {
        return $config
    }
    if (-not $config.Environments.ContainsKey($Environment)) {
        $known = ($config.Environments.Keys | Sort-Object) -join ', '
        throw "Unknown environment '$Environment'. Known environments: $known"
    }
    $envConfig = $config.Environments[$Environment]
    [pscustomobject]@{
        PSTypeName     = 'OpsKit.Environment'
        Name           = $Environment
        Region         = $envConfig.Region
        HealthUrl      = $envConfig.HealthUrl
        RequireConfirm = [bool]$envConfig.RequireConfirm
    }
}
function Invoke-OpsBackup {
    <#
    .SYNOPSIS
        Zips a folder into backup-yyyyMMdd-HHmmss.zip and keeps only the newest N backups.
    .EXAMPLE
        Invoke-OpsBackup -Source ~/pslab/data -Destination ~/pslab/backups -Keep 7 -WhatIf
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    [OutputType([System.IO.FileInfo])]
    param(
        [Parameter(Mandatory)]
        [string]$Source,

        [Parameter(Mandatory)]
        [string]$Destination,

        [ValidateRange(1, 365)]
        [int]$Keep = 7,

        [string[]]$Exclude = @('*.tmp')
    )
    $sourcePath = Resolve-OpsPath -Path $Source
    $destinationPath = Resolve-OpsPath -Path $Destination
    if (-not (Test-Path -LiteralPath $sourcePath -PathType Container)) {
        throw "Invoke-OpsBackup: source folder not found: $sourcePath"
    }
    $files = @(Get-ChildItem -LiteralPath $sourcePath -File -Recurse -Force | Where-Object {
            $name = $_.Name
            -not ($Exclude | Where-Object { $name -like $_ })
        })
    $zipPath = Join-Path $destinationPath ('backup-{0}.zip' -f (Get-Date -Format 'yyyyMMdd-HHmmss'))

    if ($PSCmdlet.ShouldProcess($zipPath, "Create backup of $($files.Count) file(s) from $sourcePath")) {
        $null = New-Item -ItemType Directory -Path $destinationPath -Force
        $archive = [System.IO.Compression.ZipFile]::Open($zipPath, [System.IO.Compression.ZipArchiveMode]::Create)
        try {
            foreach ($file in $files) {
                $entryName = [System.IO.Path]::GetRelativePath($sourcePath, $file.FullName).Replace('\', '/')
                $null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($archive, $file.FullName, $entryName)
            }
        } finally {
            $archive.Dispose()
        }
        Write-OpsLog -Message "Backup created: $zipPath ($($files.Count) files)"
        Get-Item -LiteralPath $zipPath
    }

    $expired = Get-ChildItem -LiteralPath $destinationPath -Filter 'backup-*.zip' -File -ErrorAction Ignore |
        Sort-Object -Property Name -Descending |
        Select-Object -Skip $Keep
    foreach ($old in $expired) {
        if ($PSCmdlet.ShouldProcess($old.FullName, 'Remove expired backup')) {
            Remove-Item -LiteralPath $old.FullName
            Write-OpsLog -Message "Removed expired backup: $($old.Name)"
        }
    }
}
function Get-OpsCloudInventory {
    <#
    .SYNOPSIS
        Lists Azure resources that carry the OpsKit tags, as flat objects.
    .EXAMPLE
        Get-OpsCloudInventory -Tag @{ app = 'opskit'; env = 'prod' }
    #>
    [CmdletBinding()]
    param(
        [hashtable]$Tag = @{ app = 'opskit' }
    )
    if (-not (Get-Command -Name Get-AzResource -ErrorAction Ignore)) {
        throw 'Get-OpsCloudInventory needs the Az.Resources module and a signed-in context (Connect-AzAccount).'
    }
    foreach ($resource in Get-AzResource -Tag $Tag) {
        [pscustomobject]@{
            PSTypeName = 'OpsKit.CloudResource'
            Name       = $resource.Name
            Type       = $resource.ResourceType
            Location   = $resource.Location
            Env        = if ($resource.Tags) { $resource.Tags['env'] } else { $null }
        }
    }
}
function Resolve-OpsPath {
    <# Expands a leading ~ and returns a full provider path (the target does not have to exist). #>
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [string]$Path
    )
    if ($Path -eq '~') {
        return $HOME
    }
    if ($Path -match '^~[\\/]') {
        $Path = Join-Path $HOME $Path.Substring(2)
    }
    $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
}
function Write-OpsLog {
    <# Writes a structured log entry: always to the verbose stream, and as a JSON line when a log file is set. #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Message,

        [ValidateSet('Verbose', 'Information', 'Warning', 'Error')]
        [string]$Level = 'Information',

        [string]$LogPath = $env:OPSKIT_LOG
    )
    Write-Verbose "[$Level] $Message"
    if ($LogPath) {
        $entry = [ordered]@{
            Time    = [datetime]::UtcNow.ToString('o')
            Level   = $Level
            Message = $Message
        }
        Add-Content -LiteralPath $LogPath -Value ($entry | ConvertTo-Json -Compress) -Encoding utf8
    }
}
BeforeAll {
    $manifestPath = Join-Path $PSScriptRoot '../OpsKit.psd1'
    $manifest = Test-ModuleManifest -Path $manifestPath
    Import-Module $manifestPath -Force
}

Describe 'OpsKit module' {
    It 'has a valid manifest with a SemVer version' {
        $manifest.Version | Should-NotBeNull
        [semver]::new($manifest.Version.ToString()) | Should-NotBeNull
    }
    It 'exports exactly the functions in Public/' {
        $public = (Get-ChildItem -Path (Join-Path $PSScriptRoot '../Public') -Filter '*.ps1').BaseName | Sort-Object
        (Get-Command -Module OpsKit).Name | Sort-Object | Should-BeCollection $public
    }
    It '<Name> has comment-based help with an example' -ForEach @(
        (Get-ChildItem -Path (Join-Path $PSScriptRoot '../Public') -Filter '*.ps1').BaseName | ForEach-Object { @{ Name = $_ } }
    ) {
        $help = Get-Help $Name
        $help.Synopsis | Should-NotBeWhiteSpaceString
        @($help.Examples.Example).Count | Should-BeGreaterThan 0
    }
}

Test-OpsEndpoint、Invoke-OpsApi、Invoke-OpsHealthCheck 及其测试见模块 4;Get-OpsServer、Get-OpsConfig、Invoke-OpsBackup 的测试见模块 3。

交互式排错树:“构建变红了”

目标:在你的机器上发布 OpsKit 1.0.0。环境:pwsh 7.6、Pester 6.2.0、PSScriptAnalyzer 1.25.0、PSResourceGet 1.2.x。费用:无。

测试:把模块 3、4、8 中的 9 个测试文件复制到 ~/pslab/OpsKit/tests;Invoke-Pester ./tests → 51 个通过。
分析:加入 PSScriptAnalyzerSettings.psd1;运行 ./build.ps1 -Task Analyze;用 Invoke-Formatter -Settings 或手动修复,直到看到 “Analyze: 0 findings.”。
版本:在 CHANGELOG.md 中加入 1.0.0 条目;如有空的 Prerelease = '' 先删除;Update-PSModuleManifest -Path ./OpsKit.psd1 -ModuleVersion 1.0.0;Test-ModuleManifest ./OpsKit.psd1。
构建:pwsh -NoProfile -NonInteractive -File ./build.ps1; "exit=$LASTEXITCODE" → Build succeeded.、exit=0,以及 out/repo/OpsKit.1.0.0.nupkg。
冒烟测试(可选,会修改你的仓库列表):按“命令”页第 7 步把 out/repo 注册为文件夹仓库并安装;之后用 Unregister-PSResourceRepository OpsKitLocal 和 Uninstall-PSResource OpsKit 撤销。
清理:Remove-Item ./out -Recurse(只是构建输出,每次构建都会重新生成)。

案例 1:包里带上了测试数据和 API 密钥

问题:一个团队把 Publish-Module -Path 指向仓库根目录来发布模块;包中包含了 tests/、一个 .env 文件和 out/。修复:像 build.ps1 那样暂存一个明确的允许列表(清单、根模块、Public、Private、CHANGELOG),在 CI 中检查 .nupkg 的内容,并轮换密钥。

案例 2:过时的模块导致“在我机器上能跑”

问题:本地测试针对已安装的 OpsKit 0.5 通过了,而源码中有缺陷。根因:测试文件使用 Import-Module OpsKit(按名称导入)。修复:测试按路径导入("$PSScriptRoot/../OpsKit.psd1" -Force),与 OpsKit 的测试完全一样。

案例 3:版本升级重写了整个清单

问题:一个发布拉取请求只改了版本号,却显示 130 行的清单 diff。根因:Update-PSModuleManifest 会重新生成文件。修复:一次性接受重新生成的布局(单独提交),或在 build.ps1 中用定点文本替换升级版本,再用 Test-ModuleManifest 校验。

常见错误与修复

Build failed: Analyze: N finding(s).

阅读消息上方的表格;逐条修复或说明理由。Invoke-Formatter -Settings ./PSScriptAnalyzerSettings.psd1 可以修复布局类规则。

Build failed: Test: coverage 72.5% is below the 80% threshold.
$c = New-PesterConfiguration; $c.Run.Path = './tests'; $c.Run.PassThru = $true
$c.CodeCoverage.Enabled = $true; $c.CodeCoverage.Path = './Public', './Private'
(Invoke-Pester -Configuration $c).CodeCoverage.CommandsMissed | Format-Table File, Line, Command
Compress-PSResource: … module manifest … is not valid / 缺少必需的元数据

原因:暂存目录名必须与清单名一致,且清单需要 Author 和 Description。修复:暂存到 out/stage/OpsKit;先运行 Test-ModuleManifest。

Package: …OpsKit.1.0.0.nupkg was not created.

原因:文件名中的版本来自清单;有预发布标签时文件名是 OpsKit.1.0.0-rc1.nupkg。修复:根据 Version 和 Prerelease 构造期望的文件名。

命令行练习
1. 给 build.ps1 加一个删除 out/ 的 Clean 任务。
function Invoke-CleanTask {
    Remove-Item -LiteralPath $out -Recurse -Force -ErrorAction Ignore
    Write-Host 'Clean: removed out/.'
}
# 并把 'Clean' 加入 -Task 的 ValidateSet
2. 列出生成的 .nupkg 中的文件。
$zip = [System.IO.Compression.ZipFile]::OpenRead((Resolve-Path ./out/repo/OpsKit.1.0.0.nupkg))
$zip.Entries.FullName | Sort-Object; $zip.Dispose()
场景分析
发布后第二天,一位用户报告:在他们角色用分号分隔的旧 CSV 上,Get-OpsServer -Role api 不再返回 edge-01。这是缺陷吗?你应该发布什么版本?

1.0.0 改变了角色解析(CHANGELOG:“Role as an array”,按逗号分割)。如果分号分隔的角色曾被文档化或被广泛使用,这就是回归:改为按 [,;] 分割,为两种分隔符都加测试用例,发布 1.0.1(PATCH:修复缺陷,API 不变)。如果从未支持过分号,就把格式写进文档,并考虑发布一个新增 -RoleSeparator 参数的 MINOR 版本。无论哪种情况,都先把出错的输入写成测试。

已验证的教学视频

▶
CODE2327LV: Build and Publish a PowerShell Module to the PowerShell Gallery — VMware {code}
英文 · 端到端构建并发布模块
▶
Streamline Module Publishing to PowerShell Gallery Using GitHub Actions — Jeff Brown Tech
英文 · 自动化发布

这些视频使用 PowerShellGet 的 Publish-Module;本课使用 PowerShell 7.6 自带的 PSResourceGet(Compress-PSResource、Publish-PSResource)。

官方文档

视频分镜(约 90 秒)

镜头 1 · 0–30 秒
画面:三道门 —— Analyze、Test、Package;OpsKit 0.5 在第一道门被弹回(3 条告警)。
旁白:一个构建脚本、三道门禁,你和 CI 用的完全一样。
镜头 2 · 30–60 秒
画面:覆盖率仪表从 29% 升到 100%;Monitored 缺陷被 51 个测试中的一个红色测试抓住。
旁白:覆盖率找出没测的代码;断言找出缺陷。
镜头 3 · 60–90 秒
画面:OpsKit.1.0.0.nupkg 落入文件夹仓库;标签 v1.0.0 启动工作流。
旁白:定版本、打包、打标签 —— OpsKit 1.0 发布了。
或测验得分 ≥ 70%

命令速查表

第 8 课全部要点:调试、静态分析、Pester 6 测试与 Mock、覆盖率与退出码、性能、签名与版本、CI、构建与发布
PowerShell 7.6 · Pester 6.2可复制

1. 调试

Set-PSBreakpoint -Script (Resolve-Path ./x.ps1) -Line 12
Set-PSBreakpoint -Command Remove-Item -Action { Write-Host (Get-PSCallStack)[1].Position.Text }
Set-PSBreakpoint -Variable total -Mode Write
Get-PSBreakpoint | Remove-PSBreakpoint
# [DBG]: s 进入 · v 跳过 · o 跳出 · c 继续 · k 调用栈 · l 源码 · q 退出 · ? 帮助
Wait-Debugger                       # 绝不要提交
Set-PSDebug -Trace 1   # 2 = 加上 SET/CALL;Set-PSDebug -Off
Set-StrictMode -Version Latest       # 优于 Set-PSDebug -Strict

2. PSScriptAnalyzer

Invoke-ScriptAnalyzer -Path ./src -Recurse -Settings ./PSScriptAnalyzerSettings.psd1
Invoke-ScriptAnalyzer -ScriptDefinition $code -IncludeRule PSAvoidUsing*
Get-ScriptAnalyzerRule -Severity Error
Invoke-ScriptAnalyzer ./x.ps1 -Fix          # 会改写文件
Invoke-Formatter -ScriptDefinition $code -Settings CodeFormattingOTBS
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'UI only')]
# -Path 旁边的 PSScriptAnalyzerSettings.psd1 会被自动使用!

3. Pester 6 结构

BeforeAll { Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force }   # 不要写在顶层
Describe 'Get-OpsServer' {
  Context 'filters' {
    BeforeEach { $csv = Join-Path $TestDrive 's.csv' }
    It '<Env> has <Count>' -ForEach @(@{ Env = 'dev'; Count = 2 }) { … }
  }
}
Invoke-Pester ./tests -Output Detailed -FullNameFilter '*WhatIf*'
Import-Module Pester -MinimumVersion 6.0.0           # 而不是系统自带的 3.4.0

4. 断言

$x | Should-Be 5                 # 经典写法:$x | Should -Be 5
'a' | Should-BeString 'A' -CaseSensitive
$list | Should-BeCollection @(1, 2)   # 顺序任意!
$obj | Should-BeEquivalent $expected -ExcludePath Id
$items | Should-All { $_.Ok }     # 空集合会失败
{ f } | Should-Throw -ExceptionMessage '*404*' -ExceptionType ([IO.FileNotFoundException])
Should-BeNull / Should-BeTrue / Should-HaveType / Should-BeHashtable
$c.Should.DisableV5 = $true      # 禁止 Should -Be

5. Mock

Mock Invoke-WebRequest -ModuleName OpsKit { [pscustomobject]@{ StatusCode = 200 } }   # 先写默认 Mock
Mock Invoke-WebRequest -ModuleName OpsKit -ParameterFilter { $Uri.Host -eq 'down' } { … }
Should-Invoke Invoke-WebRequest -ModuleName OpsKit -Times 1 -Exactly -ParameterFilter { $TimeoutSec -eq 2 }
Should-NotInvoke Remove-Item -ModuleName OpsKit
InModuleScope OpsKit -Parameters @{ P = '~' } { Resolve-OpsPath $P }
Mock git { 'main' }                                      # 原生命令也可以
function global:Get-AzResource { param($Tag) }; Mock Get-AzResource …   # 未安装的命令
# Pester 6:过滤器不匹配 + 没有默认 Mock = 报错

6. 覆盖率、结果、退出码

$c = New-PesterConfiguration
$c.Run.Path = './tests'; $c.Run.PassThru = $true
$c.Run.Exit = $true          # 退出码 = 失败数(或用 Run.Throw)
$c.CodeCoverage.Enabled = $true; $c.CodeCoverage.Path = './Public', './Private'
$c.CodeCoverage.OutputFormat = 'JaCoCo'     # 或 Cobertura
$c.TestResult.Enabled = $true; $c.TestResult.OutputFormat = 'NUnitXml'   # NUnit3、JUnitXml
$r = Invoke-Pester -Configuration $c
if ($r.CodeCoverage.CoveragePercent -lt 80) { exit 1 }   # 只设目标不会失败
Invoke-Pester -CI            # TestResult + Exit(不含覆盖率)

7. 性能

(Measure-Command { … }).TotalMilliseconds   # 预热,取 N 次最好
$a = foreach ($i in $in) { f $i }        # 不要 $a += …
$l = [System.Collections.Generic.List[string]]::new(); $l.Add('x')
$lines -join "`n"                         # 不要 $s += …
$sb = [System.Text.StringBuilder]::new(); $null = $sb.Append('x')
$data.Where({ $_ -gt 5 })                 # 内存中,不走管道
Get-ChildItem -Filter *.log               # 尽早筛选(不是 -Include)

8. 发布

Get-AuthenticodeSignature ./x.ps1        # Valid / NotSigned / HashMismatch
Set-AuthenticodeSignature ./x.ps1 -Certificate $cert -TimestampServer $ts
$ExecutionContext.SessionState.LanguageMode
[semver]'1.0.0-rc.1' -lt [semver]'1.0.0'  # True
Update-PSModuleManifest ./OpsKit.psd1 -ModuleVersion 1.0.0 [-Prerelease rc1]
Compress-PSResource -Path ./out/stage/OpsKit -DestinationPath ./out/repo
Publish-PSResource -Path ./out/stage/OpsKit -Repository PSGallery -ApiKey $env:PSGALLERY_API_KEY
pwsh -NoProfile -NonInteractive -File ./build.ps1; $LASTEXITCODE

综合实验 + 结业测验

端到端运行 OpsKit 1.0.0 的发布构建,用三种不同方式破坏它,证明每道门禁都能抓住对应的问题
约 25 分钟仅本地综合 M1–M8

场景

你是 OpsKit 的发布工程师。在打 v1.0.0 标签之前,你必须证明 build.ps1 在干净的代码树上通过,并且在以下情况下以退出码 1 和清晰的消息失败:(a) 某个函数被破坏,(b) 代码违反分析配置,(c) 测试缺失导致覆盖率低于 80%。不允许修改机器状态:一切都在 ~/pslab/OpsKit 中运行。

1. 干净构建(M2、M3、M5、M8):
Set-Location ~/pslab/OpsKit
Remove-Item ./out -Recurse -Force -ErrorAction Ignore
pwsh -NoProfile -NonInteractive -File ./build.ps1; "exit=$LASTEXITCODE"
==> Analyze
Analyze: 0 findings.
==> Test

Running tests from 9 files.
Starting code coverage.
[+] …\Get-OpsCloudInventory.Tests.ps1 1.26s (2 tests)
[+] …\Get-OpsConfig.Tests.ps1 395ms (6 tests)
[+] …\Get-OpsServer.Tests.ps1 390ms (9 tests)
[+] …\Invoke-OpsApi.Tests.ps1 613ms (6 tests)
[+] …\Invoke-OpsBackup.Tests.ps1 600ms (7 tests)
[+] …\Invoke-OpsHealthCheck.Tests.ps1 275ms (3 tests)
[+] …\OpsKit.Module.Tests.ps1 390ms (9 tests)
[+] …\Private.Tests.ps1 183ms (4 tests)
[+] …\Test-OpsEndpoint.Tests.ps1 398ms (5 tests)
Tests completed in 4.55s
Tests Passed: 51, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0
Processing code coverage result.
Covered 100% / 80%. 167 analyzed Commands in 9 Files.
Test: 51 passed, coverage 100% (threshold 80%).
==> Package
Package: C:\Users\labadmin\pslab\OpsKit\out\repo\OpsKit.1.0.0.nupkg (10808 bytes).
Build succeeded.
exit=0
2. 破坏一个函数(M3、M4):把 Get-OpsServer.ps1 中的 -eq 'true' 改成 -eq 'yes',只运行 Test 任务:
Set-Location ./OpsKit
$file = './Public/Get-OpsServer.ps1'
$original = Get-Content -LiteralPath $file -Raw
(Get-Content -LiteralPath $file -Raw).Replace("-eq 'true'", "-eq 'yes'") | Set-Content -LiteralPath $file -NoNewline
try {
    pwsh -NoProfile -NonInteractive -File ./build.ps1 -Task Test 2>&1 | Select-String -Pattern '\[-\]|Expected|Tests Passed|Build failed'
    "exit=$LASTEXITCODE"
} finally {
    Set-Content -LiteralPath $file -Value $original -NoNewline
}
[-] Get-OpsServer.with filters.returns only monitored servers with -MonitoredOnly 50ms
 Expected all items in collection to pass filter { $_.Monitored -eq $true }, but [Object[]] @() contains no items to 
compare.
Tests Passed: 50, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0
Build failed: Test: 1 test(s) failed.
exit=1

然后加强测试套件:加上 @(Get-OpsServer -Path $csv -MonitoredOnly).Count | Should-Be 3,确认被破坏的版本现在会让两个测试失败。

3. 破坏代码风格(M2):在某个 Public 文件中把 catch 单独放一行,运行 ./build.ps1 -Task Analyze:预期出现一条 PSPlaceCloseBrace 告警和 exit=1(同模块 8 第 3 步)。用 Invoke-Formatter 修复。
4. 降低覆盖率(M5):把 tests/Invoke-OpsApi.Tests.ps1 移到 ~/pslab/tmp,运行 ./build.ps1 -Task Test -CoverageThreshold 90:测试通过,覆盖率 85.63%,构建打印 “Test: coverage 85.63% is below the 90% threshold.” 并以 1 退出(已验证)。把文件移回去。
5. 调试一个失败(M1):在第 2 步的缺陷仍存在时,导入模块,设置 Set-PSBreakpoint -Script (Resolve-Path ./Public/Get-OpsServer.ps1).Path -Line 32(-MonitoredOnly 检查所在行),然后调用 Get-OpsServer -Path ~/pslab/data/servers.csv -MonitoredOnly。在 [DBG] 提示符下输入 $row.Monitored 和 $server.Monitored —— 字符串是 true,布尔值却是 False。用 q 退出,删除断点并还原代码。

这里要用交互式停止,而不是 -Action:已在 7.6.10 上验证,模块函数内部某行上的 Action 对 $row 和 $server 打印的都是空值(Action 运行在调用方的会话状态中,而不是模块的),而在干净的模块上 [DBG] 提示符显示的是 web-01 和 True。

6. 测量(M6):Measure-Command { 1..50 | ForEach-Object { Get-OpsServer -Path ~/pslab/data/servers.csv } } —— 记下耗时;以后有人报告 Get-OpsServer 慢时,这就是你的基线。
7. 发布元数据(M7):确认 Test-ModuleManifest ./OpsKit.psd1 报告 1.0.0,CHANGELOG 有 1.0.0 条目,.github/workflows/opskit.yml 能被解析,Get-AuthenticodeSignature 显示预期状态(实验中为 NotSigned)。
验收标准

开放式自检

1. 一个测试文件在 VS Code 测试资源管理器中通过,在 CI 中却报 “Expected 12, but got 0”。给出两个最可能的原因。

发现阶段的初始化(资源管理器的运行方式可能掩盖了它,或在 Pester 5 语义下变量从别的文件泄漏过来;Pester 6 的按文件发现会把它暴露出来),或代理上的 Pester 版本不同(在 CI 日志中检查 Get-Module Pester)。把初始化移入 BeforeAll,并固定/导入 Pester ≥ 6。

2. 为什么 OpsKit 的测试套件在带过滤器的 Mock 之前先定义默认 Mock?

在 Pester 6 中,不匹配任何过滤器且没有默认 Mock 的调用会抛错。默认 Mock 记录了“正常”的应答;带过滤器的 Mock 描述例外情况。

3. 构建是绿的,但用户报告了崩溃。哪道门禁失效了?流程该怎么改?

没有哪道门禁“失败”—— 测试根本没有断言那个出问题的行为。先用一个失败的测试复现,修复,发布 PATCH,并把该用例加入套件;考虑对具体值做断言,而不只检查形状/类型;如果崩溃涉及真实 I/O,再加一个集成测试。

4. 什么情况下 Set-PSDebug -Trace 2 不安全?

当代码处理机密时:! SET 行会把变量值打印到日志中。

来源与版本说明

版本事实于 2026-11-24 对照 PowerShell Gallery、Pester GitHub 发布页、Microsoft Learn 和 GitHub API 核实;命令输出在 PowerShell 7.6.10、Pester 6.2.0 和 PSScriptAnalyzer 1.25.0 上生成
验证日期 2026-11-24
主题核实结果来源(访问于 2026-11-24)
Pester 版本Gallery:当前为 Pester 6.2.0(2026-09-09 发布);6.1.0(2026-08-11)、6.0.0(2026-07-07)。Windows 在 C:\Program Files\WindowsPowerShell\Modules 中自带 Pester 3.4.0,pwsh 可见Find-PSResource Pester;Pester 6.2.0 发布
Pester 6 变化Should-* 断言(6.2.0 中 41 个命令);按文件发现与运行;默认分析器覆盖率、Cobertura、移除 CoverageGutters;移除 Assert-MockCalled、Pending、-Focus、Mock 回落;空 -ForEach 抛错;6.2:每块可有多个 BeforeAll、配置校验6.0.0 发布说明;6.1.0;6.2.0;本课复现
复现的 Pester 行为发现阶段的变量在运行时为 $null;Should-BeCollection 忽略顺序;不匹配的过滤 Mock 抛错;-ParameterFilter 能匹配 TimeoutSec 别名;Run.Exit 在 2 个失败时退出码为 2;覆盖率目标不强制;-CI 不含覆盖率实际运行(输出见模块 3–5)
PSScriptAnalyzer1.25.0(2026-03-20);75 条规则:8 Error、56 Warning、11 Information;被分析路径旁的 PSScriptAnalyzerSettings.psd1 会被自动应用;Show 动词函数豁免 PSAvoidUsingWriteHost;位置参数规则需要 3 个及以上参数概述;使用 PSScriptAnalyzer;实际运行
调试器断点类型、调试器命令、Wait-Debugger、Set-PSDebug;-Action 中 $PSDebugContext 为 $null,且 Action 看不到模块函数的局部变量;变量断点的 Action 看到写入后的值;-Strict 忽略字符串中的变量about_Debuggers;Set-PSBreakpoint;Set-PSDebug;实际运行
VS Code 启动配置扩展 package.json(2026.1.2 版)中的 “Launch Current File”(script: ${file})、“Launch Script”、“Attach to PowerShell Host Process” 代码片段GitHub PowerShell/vscode-powershell package.json;使用 VS Code
性能模块 6 的耗时来自一台 Windows 11 机器(3 次取最好)性能注意事项;实际运行
签名与语言模式对 OpsKit(NotSigned)和 PSResourceGet(Valid,Microsoft)运行 Get-AuthenticodeSignature;CLM 对方法调用、Add-Type 和 [pscustomobject] 报错about_Signing;about_Language_Modes;实际运行
版本与打包[version] 拒绝标签;[semver] 排序(含 rc2 与 rc10);PSResourceGet 1.2.1 的 Update-PSModuleManifest 在 Prerelease = '' 时失败;Compress-PSResource 生成了 OpsKit.1.0.0.nupkgUpdate-PSModuleManifest;Compress-PSResource;预发布版本;semver.org
GitHub Actionsactions/checkout v7.0.1(2026-07-20)和 actions/upload-artifact v7.0.2(2026-10-07)为最新;工作流 YAML 用 powershell-yaml 0.4.12 解析,每个 run: 块都按 PowerShell 解析;未实际执行GitHub REST API 发布信息;工作流语法

视频核实说明

本课只列出 2026-11-24 通过 YouTube oEmbed 核实过标题和频道的视频:

oEmbed 只能核实标题和频道;视频没有逐段观看。这些视频都早于 Pester 6,多数使用 PowerShellGet 而非 PSResourceGet —— 存在差异时,以本课经过验证的输出为准。没有找到讲解 Pester 6 的 Should-* 断言或 Mock 变化、Pester 6 覆盖率/退出码配置、Authenticode 签名或受限语言模式的已验证视频。

语音讲解说明

“语音”分页使用浏览器内置的 Web Speech API(zh-CN)朗读讲解稿;无需网络访问或外部脚本。本课件无法嵌入 MP3 或生成视频;讲解稿和分镜可交给 TTS 或视频工具使用。

已知限制

  • 运行环境:所有“实际输出”均来自 Windows 11 上的 PowerShell 7.6.10。Pester 6.2.0 和 PSScriptAnalyzer 1.25.0 是用 Save-PSResource 保存到文件夹、通过 $env:PSModulePath 加载的,而不是安装的;路径被改写为 C:\Users\labadmin\pslab\…,TestDrive 临时路径改写为 …\AppData\Local\Temp\…,JUnit 示例中的主机名和用户名已替换。未在 Linux 或 macOS 上运行。
  • 未执行(预期输出):创建自签名证书并签名(会修改证书存储)、注册文件夹仓库并从中安装(会修改用户的 PSResourceGet 仓库列表)、发布到 PowerShell Gallery、运行 GitHub Actions 工作流,以及 VS Code 调试器界面。控制台调试器会话是真实的,通过重定向标准输入驱动。
  • OpsKit 代码是第 3–7 课所建内容的精简重建版(函数名和参数相同);尤其是 Invoke-OpsHealthCheck 在这里是顺序执行的,Get-OpsCloudInventory 是对 Get-AzResource 的薄封装,只用 Mock 测试。
  • 性能数字来自一台机器上一次“3 次取最好”的测量;绝对值会有所不同。
  • 动画简化了引擎和 Pester 的内部机制(Mock 代理生成、发现容器、GitHub 的作业调度)。