画面:一个满是
Write-Host "x=$x" 的脚本,这些行被逐一删除;第 6 行出现一个红点。旁白:别再猜了 —— 让脚本停在出错的地方。
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” 配置。PSScriptAnalyzerSettings.psd1 控制它(并且知道同名文件会被自动加载),用带理由的特性抑制单条告警,用 Invoke-Formatter 格式化代码。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 尽早筛选。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。| # | 时间 | 模块 | 核心内容 | 动画 / 交互 | 实验(~/pslab) |
|---|---|---|---|---|---|
| 0 | 课前 | 准备 | Pester 6.2.0 和 PSScriptAnalyzer 1.25.0 与系统自带的 Pester 3.4.0 并存;VS Code PowerShell 扩展;OpsKit v0.5 目录结构 | 自检清单 | 加载正确的 Pester,运行第一个测试 |
| 1 | 00–06 | 调试 | Set-PSBreakpoint(行、命令、变量)、调试器命令、$PSDebugContext、Wait-Debugger、Set-PSDebug -Trace / -Strict、Write-Debug、launch.json | 调试器单步演示:s / v / o / c | 用断点和 Action 找出错误的统计结果 |
| 2 | 06–13 | 静态分析 | Invoke-ScriptAnalyzer、严重级别、配置文件、自动加载、抑制、Invoke-Formatter、-Fix | 分析器流水线 | 清理一个故意写坏的脚本 |
| 3 | 13–21 | Pester 基础 | Describe / Context / It、BeforeAll / BeforeEach、发现与运行、Should-* 与 Should -Be、TestDrive、-ForEach | 核心动画:发现阶段与运行阶段 | 为 Get-OpsServer 和 Invoke-OpsBackup 写测试 |
| 4 | 21–28 | Mock | Mock -ModuleName -ParameterFilter、Should-Invoke、InModuleScope、测试 -WhatIf 与错误、原生命令、REST 重试 | Mock 解析器 | 不联网测试 Test-OpsEndpoint 和 Invoke-OpsApi |
| 5 | 28–35 | 覆盖率与 CI 输出 | New-PesterConfiguration、CodeCoverage(JaCoCo)、TestResult(NUnitXml / JUnitXml)、Run.Exit、Run.Throw、-CI | 从测试运行到 CI 状态 | 为 OpsKit 生成覆盖率和结果文件 |
| 6 | 35–42 | 性能 | Measure-Command;+= vs List[T] vs $x = foreach;StringBuilder;.Where();foreach vs ForEach-Object;-Filter | 开销赛跑 | 在自己机器上对比六种写法 |
| 7 | 42–50 | 安全与发布 | Authenticode、AllSigned、受限语言模式、SemVer + Prerelease、CHANGELOG、GitHub Actions 矩阵与发布 | 发布流水线 | 编写并校验 .github/workflows/opskit.yml |
| 8 | 50–60 | OpsKit v1.0 | 测试套件、分析告警清理、Update-PSModuleManifest、build.ps1、Compress-PSResource、本地文件夹仓库 | build.ps1 守门人 + 排错树 | 发布 OpsKit 1.0.0 |
| — | 课后 | 速查表 · 综合实验 | 端到端运行 build.ps1,故意破坏它,逐项核对验收标准 | 结业测验(12 题) | out/repo 中的 OpsKit.1.0.0.nupkg |
| 目标技能 | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | 关键命令 | 实验 |
|---|---|---|---|---|---|---|---|---|---|---|
| 交互式与无人值守调试 | ✓ | · | · | · | · | · | · | ✓ | Set-PSBreakpoint、Wait-Debugger、Set-PSDebug | M1 |
| 静态分析与格式化 | · | ✓ | · | · | · | · | ✓ | ✓ | Invoke-ScriptAnalyzer、Invoke-Formatter | M2、M8 |
| 编写 Pester 6 测试 | · | · | ✓ | ✓ | ✓ | · | · | ✓ | Describe、It、Should-Be、TestDrive | M3、M8 |
| 用 Mock 隔离依赖 | · | · | · | ✓ | · | · | · | ✓ | Mock、Should-Invoke、InModuleScope | M4、M8 |
| 覆盖率、报告与退出码 | · | · | · | · | ✓ | · | ✓ | ✓ | New-PesterConfiguration、Run.Exit | M5、综合实验 |
| 测量并修复性能问题 | · | · | · | · | · | ✓ | · | · | Measure-Command、List[T]、-Filter | M6 |
| 签名、版本与发布文档 | · | · | · | · | · | · | ✓ | ✓ | Get-AuthenticodeSignature、[semver]、Update-PSModuleManifest | M7、M8 |
| 自动化构建与 CI | · | ✓ | · | · | ✓ | · | ✓ | ✓ | build.ps1、GitHub Actions、Compress-PSResource | M8、综合实验 |
| 主题 | 为什么不在本课 | 去哪里学 |
|---|---|---|
编写自定义 PSScriptAnalyzer 规则、自定义 Should-* 断言(New-ShouldAssertion) | 面向工具作者;内置规则和断言已足够覆盖 OpsKit | PSScriptAnalyzer 文档;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 课 |
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 的所有耗时都来自同一台机器,你的结果会不同。SupportsShouldProcess)。第 7 课的 Invoke-OpsApi 在这里用 Mock 测试,因此不需要 API 或云账号。~/pslab/data 中生成的数据集(随时可用 ~/pslab/New-LabData.ps1 重建)。pwsh 中即可完成。[CmdletBinding(SupportsShouldProcess)] 给函数带来了什么?函数体必须调用什么?带来 -WhatIf 和 -Confirm 参数;函数体必须把每一处修改包在 if ($PSCmdlet.ShouldProcess($target, $action)) { … } 中。模块 4 正是要测试这一点。
清单中的 FunctionsToExport(以及根模块的 Export-ModuleMember)。私有辅助函数留在模块内部 —— 所以测试需要 -ModuleName 或 InModuleScope(模块 4)。
pwsh -File 而不是 -Command?-File 会把脚本的 exit N 原样传给调用方;-Command 只报告 0 或 1。CI 依赖退出码(模块 5 和 8)。
常规做法是用 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。
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。
| 路径 | 内容 |
|---|---|
~/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
在 VS Code 中打开 ~/pslab/OpsKit。状态栏必须显示 PowerShell 7.6(点击版本号可切换)。扩展会在你输入时用波浪线标出 PSScriptAnalyzer 告警,并提供调试器(模块 1)。“测试”面板可以通过 Pester Tests 扩展运行 Pester 测试;本课使用命令行,以便输出可复现。
TestDrive:(每个容器结束后自动删除的临时目录)和 ~/pslab。不会向真实仓库发布任何内容,也不会创建证书:签名和发布步骤以预期输出展示。撤销准备工作:Uninstall-PSResource Pester, PSScriptAnalyzer -Version 6.2.0, 1.25.0(如果你安装过),或删除 ~/pslab/modules。不要动系统自带的 Pester 3.4.0,Windows 组件可能会用到它。Set-PSBreakpoint 设置行、命令和变量断点,列出和删除断点,并附加只记录日志、不停止的 -Action。s(单步进入)、v(单步跳过)、o(单步跳出)、c(继续)、k(调用栈)、l(列出源码)、q(退出)、?(帮助)—— 并在 [DBG] 提示符下求值任意表达式。Wait-Debugger、$PSDebugContext、Set-PSDebug -Trace 1/2 和 -Strict,以及配合 -Debug 的 Write-Debug。[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。
| 按键 | 命令 | 作用 | VS Code |
|---|---|---|---|
s | StepInto | 执行一条语句;进入它调用的函数和脚本 | F11 |
v | StepOver | 执行一条语句;被调用的函数整体执行完 | F10 |
o | StepOut | 执行完当前函数或脚本,停在调用方 | Shift+F11 |
c | Continue | 运行到下一个断点 | F5 |
q | Quit | 停止脚本并退出调试器 | Shift+F5 |
k | Get-PSCallStack | 显示调用栈 | CALL STACK 面板 |
l / l 10 5 | List | 显示当前行附近的源码(* 标记当前行) | 编辑器 |
? / h | Help | 列出命令 | — |
| 任意表达式 | — | 在脚本作用域中求值:$s.Name、$total = 0 | DEBUG 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 更好,见“命令”页) |
Set-PSBreakpoint 在任何宿主中都能用。② “Set-PSDebug -Strict 能抓住所有未定义变量” —— 它等于严格模式 1.0,会忽略字符串内的变量(在“命令”页复现)。③ “生产代码里忘掉的 Wait-Debugger 无害” —— stdin 保持打开时会永远等待;stdin 已到 EOF 时会被悄悄跳过(两种情况都在 7.6.10 上验证过)。④ “-Debug 会对每条消息要求确认” —— 那是 Windows PowerShell 5.1 的行为;7.x 中它只是设置 $DebugPreference = 'Continue' 并打印。⑤ “编辑文件后行断点会跟着代码走” —— 断点绑定的是行号,在上方编辑会让它错位。选择一个场景并逐步执行。日志显示的是为本课录制的 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'(不再提示确认) |
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 断点是在服务器上给受变更管控的脚本加观测点的安全方式,无需修改文件。
$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。
$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 打开但无人输入时,它一直等待直到被终止。两种结果都不是生产环境想要的。
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 行跟踪 —— 短脚本还好,模块就太多了。
$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。
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
{
"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 服务器 —— 错的是条件,不是计数器。
$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 * 然后 qSet-PSDebug -Trace 1; ./scripts/buggy.ps1; Set-PSDebug -Off —— 数一数出现了多少行 DEBUG:。然后把第 4 行改为 if ($s.Env -eq 'prod'),确认输出 prod servers: 6。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问题:一次紧急修复后,计划执行的 OpsKit 备份再也没有结束。根因:工程师排查时在脚本里留下了 Wait-Debugger;任务的 stdin 是一个打开的句柄,于是调试器永远等待。修复:删除它,在 CI 中加入检查 Select-String -Path ./**/*.ps1 -Pattern 'Wait-Debugger|Set-PSBreakpoint',命中即构建失败;并为计划任务设置运行时限。
问题:模块中的 $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 课的作用域规则在现场的表现。
问题:为了排查不稳定的流水线,有人加了 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
原因(已在 7.6.10 上验证):Action 脚本块属于创建它的会话状态(你的控制台或脚本),因此看不到在模块内运行的函数的局部变量。对 OpsKit 的 Get-OpsServer 第 32 行设置的 Action 断点对每一行都打印 Monitored='' -> ,而普通断点的 [DBG] 提示符显示 $row.Name = web-01。修复:改用交互式停止,或在函数内部用 Write-Debug 记录。
原因:命令断点(-Command Get-*)到处匹配。修复:加 -Script 限定范围,或用 v(单步跳过)代替 s。
原因:扩展连接的是 5.1,或启动失败。修复:点击状态栏中的版本号,选择 PowerShell 7.6,重启会话(命令面板 → “PowerShell: Restart Session”)。
原因:严格模式已开启,而变量拼错了或从未赋值 —— 这正是严格模式的用途。修复:改正变量名;对于可选变量,用 Test-Path Variable:x 检测或先初始化。
原因:函数缺少 [CmdletBinding()],因此 -Debug 不是参数;或 $DebugPreference 为 SilentlyContinue。修复:加上 [CmdletBinding()] 并带 -Debug 调用。
$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)。
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 -RecursePSDebugContext null? True frame: | $cs = Get-PSCallStack frame: d9.ps1 | Remove-Item -LiteralPath ./tmp/a.txt
在 -Action 中 $PSDebugContext 为 $null(已验证)—— 它只在真正的 [DBG] 停止时存在。Get-PSCallStack 可用:第 1 帧就是调用所在的那一行。
不要把调试器附加到计划运行上,而是收集证据:用 Start-Transcript、-Verbose 运行任务,必要时临时加一个带 -Action 的断点记录 Test-OpsEndpoint 的输入(不涉及机密时也可用 Set-PSDebug -Trace 1)。然后在本地复现相同条件:相同账号(runas)、pwsh -NoProfile -NonInteractive -File、相同的代理/DNS。典型根因:服务账号没有代理设置、相对路径被解析到 System32、或依赖配置文件中加载的模块(第 1 课)。
本材料无法直接生成视频或 MP3;分镜和讲解稿可交给视频工具使用。
Write-Host "x=$x" 的脚本,这些行被逐一删除;第 6 行出现一个红点。-Recurse)或字符串(-ScriptDefinition)运行 Invoke-ScriptAnalyzer,读懂 RuleName、Severity、Line。PSScriptAnalyzerSettings.psd1 控制分析 —— 并且知道放在被分析路径旁、文件名完全一致的配置会被自动使用,并覆盖 -Severity。[Diagnostics.CodeAnalysis.SuppressMessageAttribute()] 抑制单条告警;用 Invoke-Formatter 修正布局,用 -Fix 修正别名。PSScriptAnalyzer(PSSA)把脚本解析成与引擎相同的 AST,再让每条规则在 AST 上运行。它不执行任何代码,因此对不可信代码也是安全的,而且快到可以每次按键都运行 —— VS Code 扩展正是这样做的。1.25.0 版共有 75 条规则:8 条 Error、56 条 Warning、11 条 Information(在实验机上用 Get-ScriptAnalyzerRule 统计)。
| 规则(示例) | 严重级别 | 为什么重要 |
|---|---|---|
PSAvoidUsingConvertToSecureStringWithPlainText | Error | 机密出现在脚本或历史记录中 |
PSAvoidUsingPlainTextForPassword | Warning | [string]$Password 参数:应使用 [securestring] 或 [pscredential] |
PSAvoidUsingCmdletAliases | Warning | gci、%:难读,且不同平台不一致(第 1 课) |
PSAvoidUsingWriteHost | Warning | 输出无法被捕获为数据(使用 Show 动词的函数除外) |
PSUseApprovedVerbs | Warning | Fetch-Servers → Get-OpsServer;模块导入时会警告 |
PSAvoidUsingEmptyCatchBlock | Warning | 吞掉错误(第 5 课) |
PSPossibleIncorrectComparisonWithNull | Warning | $rows -eq $null 会过滤数组;应写 $null -eq $rows |
PSUseDeclaredVarsMoreThanAssignments | Warning | 只赋值从不使用:死代码或拼写错误 |
PSUseShouldProcessForStateChangingFunctions | Warning | Set-/Remove-/New- 函数缺少 SupportsShouldProcess |
PSAvoidUsingPositionalParameters | Information | 只针对可解析的命令且有 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 |
编辑器: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 审计它们。每个场景跟踪一次对 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 … | 格式化文本 | 返回字符串 |
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。
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
@{
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,让行为不依赖当前目录。
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*' 形式。
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问题:开发者运行 Invoke-ScriptAnalyzer -Path ./src -Recurse -Severity Error 看不到任何告警;CI 却因 Warning 失败。根因:CI 从仓库根目录运行,那里的 PSScriptAnalyzerSettings.psd1(Severity Error, Warning)被自动加载;本地则是在 src 中运行。修复:只用一个配置文件,并在开发者和 CI 共用的构建脚本中始终用 -Settings 传入。
问题:一个包含 ConvertTo-SecureString 'Winter2026!' -AsPlainText -Force 的脚本被合并,密码进入了 Git 历史。修复:轮换机密,改从 SecretManagement 或 CI 机密获取(第 7 课),并让 PSSA 的 Error 阻止拉取请求合并。在后续提交中删除这一行并不能把它从历史中移除。
问题:一个只改了一个条件的拉取请求显示 400 行变更,因为编辑器重新缩进了整个文件。修复:约定一个格式预设(CodeFormattingOTBS 或配置文件),在单独的“仅格式化”提交中运行一次 Invoke-Formatter,之后在 CI 中强制布局规则。
原因:模块没有为 pwsh 7 安装(或只在不在 PSModulePath 上的随项目目录中)。
Get-Module PSScriptAnalyzer -ListAvailable Install-PSResource PSScriptAnalyzer -Version 1.25.0 -Scope CurrentUser
原因:扩展使用自带的 PSSA 版本和自己的配置路径。修复:在 .vscode/settings.json 中设置 "powershell.scriptAnalysis.settingsPath": "PSScriptAnalyzerSettings.psd1",并比较 (Get-Module PSScriptAnalyzer).Version。
原因:规则名错误(必须是确切的 RuleName,如 PSAvoidUsingWriteHost),或者特性没有放在包含该告警的函数/param 块上。
原因:兼容性规则(PSUseCompatibleCommands)要加载大型配置文件;或分析了 node_modules、构建输出。修复:只分析源码目录,兼容性规则只在 CI 中启用。
Get-ScriptAnalyzerRule -Severity Error | Sort-Object RuleName | Select-Object RuleName
$r = Invoke-ScriptAnalyzer -Path ./OpsKit -Recurse -Settings ./OpsKit/PSScriptAnalyzerSettings.psd1 $r | Format-Table Severity, RuleName, ScriptName, Line -AutoSize exit [int]([bool]$r)
① 提交一个配置文件。② 在专门的机械性提交中运行 -Fix 和 Invoke-Formatter(易于评审,也易于回滚)。③ 立即对 Error 设门禁(通常数量少,且与安全相关)。④ 对 Warning 只在拉取请求的变更文件上设门禁(git diff --name-only → Invoke-ScriptAnalyzer)。⑤ 每周跟踪总数直到归零,然后全面设门禁。抑制在评审中必须附理由。
BeforeAll、Describe、Context、It、BeforeEach、AfterEach、AfterAll 组织测试文件。Describe 中的代码在发现阶段执行,等到 It 运行时变量已经不在了。Should-* 系列(Should-Be、Should-BeString、Should-BeCollection、Should-BeEquivalent、Should-Throw 等),并知道它与经典 Should -Be 的差异。TestDrive: / $TestDrive 隔离文件系统测试,用 -ForEach 和 <Name> 模板根据数据生成测试。| 关键字 | 职责 | 执行阶段 |
|---|---|---|
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、-Match | Should-BeString -CaseSensitive、-TrimWhitespace、-NormalizeLineEnding;Should-BeLikeString、Should-MatchString |
| 布尔 / null | Should -BeTrue、-BeNullOrEmpty | Should-BeTrue、Should-BeFalse、Should-BeNull、Should-BeTruthy |
| 集合 | Should -Contain、-HaveCount | Should-BeCollection(元素相同,顺序任意)、Should-ContainCollection、Should-All、Should-Any |
| 对象 | — | Should-BeEquivalent(深度比较,显示属性差异)、-ExcludePath、-ExcludePathsNotOnExpected |
| 异常 | { … } | Should -Throw -ExpectedMessage '…' | { … } | Should-Throw -ExceptionMessage '…' -ExceptionType ([…])(消息用 -like 匹配) |
| Mock | Should -Invoke | Should-Invoke、Should-NotInvoke(模块 4) |
| 关闭旧语法 | $config.Should.DisableV5 = $true 会让 Should -Be 抛错 —— 适合在测试套件迁移完成后使用 | |
$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)。选择一种测试文件布局,观察每部分在哪一遍执行。红色表示测试出错的地方;日志显示 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}) | 数据驱动测试 | 键会成为变量 |
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
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 之外不允许有可执行代码”。
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” 这个测试通过了,这正是下面要解释的意外。
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
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 变成错误。
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。费用:无。
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*"
}
}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',重新运行,读一读哪些测试失败以及原因,然后改回。问题:一个测试套件连续几个月都通过,而某个函数早已损坏。根因:文件在顶层导入模块,并在 Describe 块体中给 $expected 赋值;运行阶段 $expected 为 $null,断言 $result | Should -Be $expected 比较的是 $null 与 $null。修复:把初始化移到 BeforeAll;对测试依赖的值加 Should-NotBeNull 保护。
问题:一台 Windows 构建代理打印 “The BeforeAll command may only be used inside a Describe block.”。根因:镜像中只有系统自带的 Pester。修复:在流水线中安装固定版本,并用 -MinimumVersion 6.0.0 导入,让错误版本明确地失败。
问题:备份测试只在其他测试之后运行时失败。根因:它们共用 $TestDrive 中的一个固定路径,而前一个测试留下了 zip 文件(TestDrive 按块而不是按测试划分)。修复:在 BeforeEach 中创建唯一的子目录 —— OpsKit 的备份测试正是这样做的。
原因:加载的是 Pester 3/4。修复:Get-Module Pester;Remove-Module Pester; Import-Module Pester -MinimumVersion 6.0.0。
原因:变量是在发现阶段赋值的。修复:把它移到 BeforeAll 或 BeforeEach 中。
原因:Pester 6 拒绝空的 -ForEach(通常是发现阶段计算的数据结果为空)。修复:在 BeforeDiscovery 中正确计算数据;如果为空是合理的,加 -AllowNullOrEmptyForEach。
原因:配置(或 $PesterPreference)中设置了 Should.DisableV5 = $true。修复:迁移该断言,或把它改回 $false。
原因:Pester 6 移除了 Pending 状态。修复:使用 Set-ItResult -Skipped -Because '…' 或 -Inconclusive。
~/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
}
}Invoke-Pester -Path ./OpsKit/tests -FullNameFilter '*WhatIf*' -Output Detailed
-ForEach 用例,结果即使你只过滤出一个无关的测试,整个套件也变慢了。为什么?怎么改?顶层代码和 BeforeDiscovery 在每次运行该文件的发现阶段都会执行,即使过滤器最终排除了它的所有测试 —— 构建测试树需要这些数据。可选方案:用少量有代表性的用例(边界值、异常值)代替每一行;把批量校验移到一个在运行阶段循环的 It 中;或者给该文件打标签,在本地快速运行时排除它。让发现阶段保持轻量。
两个视频都早于 Pester 6:使用的是仍然可用的 Should -Be。没有找到讲解 Pester 6 Should-* 系列的已验证视频;请参考 Pester 6.0.0 发布说明和本模块。
-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)。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、kubectl | CI 中未安装原生工具或需要凭据 | Mock git { 'main' }(对应用程序同样有效) |
Get-AzResource | 运行器上没有安装该模块 | 先定义一个桩函数,再 Mock 它(Mock 要求命令存在) |
| 你的代码在何处调用依赖…… | Mock 写法 |
|---|---|
| 点源进测试的函数(脚本,而非模块) | Mock X { } |
模块 OpsKit 内部(公有或私有函数) | Mock X -ModuleName OpsKit { } —— 以及 Should-Invoke X -ModuleName OpsKit |
| 想直接调用私有函数 | InModuleScope OpsKit -Parameters @{ … } { Resolve-OpsPath … } |
优先通过公共接口配合 -ModuleName 测试;谨慎使用 InModuleScope(它会让测试与内部实现耦合),并用 -Parameters 传值,而不是依赖外部变量。
同一命令可以有多个 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 用原命令的参数元数据生成一个代理函数,并定义在目标会话状态中(测试作用域,或使用 -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 ([…]) | 错误路径 | 把调用包在脚本块中 |
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。
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 失败。
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 可以正常工作。生产用法:每个重试循环都应有这四个测试:成功、重试后成功、不可重试、放弃。
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
}
}
}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 —— 注意这有多慢、多不确定,然后改回来。$env:OPSKIT_LOG 在 finally 中移除)。问题:在跳板机上运行测试套件时重启了 IIS。根因:Mock Restart-Service { } 声明时没有 -ModuleName;模块内部的调用打到了真实 cmdlet。修复:对模块内部调用的每一个 Mock 都加 -ModuleName,再加 Should-Invoke … -ModuleName,这样从未命中的 Mock 会让测试失败。单元测试在构建代理上运行,不要在服务器上运行。
问题:重试测试要跑好几分钟。根因:真实的 Start-Sleep 和指数退避。修复:Mock Start-Sleep -ModuleName OpsKit { } 并断言休眠次数;如果需要端到端证明,只保留一个使用极小 -RetryDelayMs 的慢速集成测试。
问题:升级后大量测试报 “No mock for command … matched the call”。根因:它们依赖 v5 在过滤器不匹配时回落到真实命令。修复:为每个命令添加默认 Mock(通常是 { }),这也让测试对其允许的每一次调用都更诚实。
原因:调用发生在模块内部,而 Mock 或断言缺少 -ModuleName。修复:两者都加上 -ModuleName OpsKit。
原因:Pester 6 移除了回落。修复:在带过滤器的 Mock 之前加一个默认的 Mock X { };错误消息会列出已评估的过滤器和绑定的参数。
原因:无法 Mock 一个不存在的命令。修复:定义一个带所用参数的桩函数(全局,或通过 InModuleScope 放在模块内),再 Mock 它;在 AfterAll 中删除。
原因:脚本块在模块的作用域中运行。修复:用 -Parameters @{ Path = $Path } 传值(它们会成为块内变量)。
原因:每个运行空间有自己的会话状态。修复:把函数设计成并行部分可注入(提供 -ThrottleLimit 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 OpsKitGet-Date,只有带 -Format 调用时才返回固定日期。Mock Get-Date -ModuleName OpsKit -ParameterFilter { $Format } { '20261124-101500' }
Mock Get-Date -ModuleName OpsKit { [datetime]'2026-11-24T10:15:00' } # 其他调用的默认 MockBeforeAll 中启动本地 HttpListener 来测试 Invoke-OpsApi;另一位只想用 Mock。你怎么建议?两者都要,但层级不同。用 Mock 的单元测试在毫秒级证明逻辑(重试规则、请求体序列化、-WhatIf),且从不随机失败。再加一两个针对第 7 课 127.0.0.1 上模拟 API 的集成测试,证明真实的 HTTP 链路(请求头、JSON 解析、异常类型)。给集成测试打标签(-Tag Integration),让 CI 在单独的作业中运行,开发者本地可以排除它们。
两者都早于 Pester 6(没有 Should-Invoke,回落行为仍然存在)。没有找到讲解 Pester 6 Mock 变化的已验证视频。
New-PesterConfiguration 构建一次运行:Run.Path、Run.PassThru、Output.Verbosity、CodeCoverage.*、TestResult.*。CoveragePercent 和未覆盖的命令。Run.Exit(退出码 = 失败测试数)、Run.Throw 和 -CI —— 并且知道覆盖率低于目标值本身不会让运行失败。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.Verbosity | None、Normal、Detailed、Diagnostic | Normal |
Output.CIFormat | Auto、AzureDevops、GithubActions(错误注解) | Auto |
CodeCoverage.Enabled / Path / OutputFormat / OutputPath | 对这些文件统计覆盖率,输出 JaCoCo 或 Cobertura | 关闭;JaCoCo;coverage.xml |
CodeCoverage.CoveragePercentTarget | 摘要中显示的目标值 | 75 |
CodeCoverage.UseBreakpoints | 旧的基于断点的覆盖率 | $false(6.0 起基于分析器) |
TestResult.Enabled / OutputFormat / OutputPath | NUnitXml、NUnit2.5、NUnit3、JUnitXml | 关闭;NUnitXml;testResults.xml |
Should.DisableV5 | 禁止 Should -Be | $false |
退出码决定步骤变红还是变绿。测试结果文件让 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 -CI | TestResult.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 文件);把它们当作构建产物,而不是公开文档。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 |
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())。
<?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 目录推断)。
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.
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 0pwsh -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。问题:一条流水线连续两周保持绿色,而有 3 个测试失败。根因:步骤运行的是 pwsh -c "Invoke-Pester ./tests" —— 失败被打印出来,但退出码是 0。修复:Run.Exit = $true(或 -CI),再加上测试结果文件,让 CI 系统醒目地显示失败。
问题:没有人删测试。根因:有人把 CodeCoverage.Path 设成了 '.',构建脚本和随项目携带的模块都进了分母。修复:只列出模块的源码目录,并保持 ExcludeTests 开启。
问题:一个开源项目把 NUnit 结果附在公开的发布中。根因:结果文件包含机器名、用户和工作目录。修复:把它们作为有保留期限的 CI 产物,而不是发布附件。
原因:CodeCoverage.Path 指向的文件并不是测试导入的那些(out/stage 中的副本、PSModulePath 中的其他模块版本)。修复:从你统计覆盖率的同一目录按路径导入模块。
原因:报告格式与 CI 的报告器不匹配(JUnit 与 NUnit),或失败时没有上传文件。修复:让 TestResult.OutputFormat 与报告器匹配;用 if: always() 上传。
原因:6.2 会校验配置值而不是悄悄忽略(发布说明)。修复:阅读 [PesterConfiguration]::Default.节.选项.Description 了解允许的值。
原因:Pester 6 默认使用分析器跟踪器。修复:接受新的基线,或临时设置 CodeCoverage.UseBreakpoints = $true 进行对比。
$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
$r.CodeCoverage.CommandsMissed | Group-Object File -NoElement | Sort-Object Count -Descending | Select-Object -First 3
没有。命令覆盖率只证明每条语句运行过,不证明测试检查了正确的结果,也不证明每种分支组合和错误路径都被执行过。OpsKit 覆盖率是 100%,但一个真实缺陷之所以被发现,只是因为 Should-All 对空集合会失败(模块 8)。更好的目标:每个公有函数都有覆盖正常路径、每种文档化错误、-WhatIf 和边界值的测试;覆盖率是发现未测代码的烟雾报警器,而不是质量分数。
没有找到专门讲解 Pester 6 配置、覆盖率格式或退出码的已验证视频;请参考 Pester 文档和本模块经过验证的输出。
Measure-Command 计时(预热、多次取最好、输出被丢弃、作用域影响)。+=、List[T].Add() 和管道捕获($a = foreach (…) { … }),以及字符串 +=、StringBuilder 和 -join。ForEach-Object、foreach 与 .ForEach(),以及 Where-Object 与 .Where()。-Filter 胜过 Where-Object,而 -Include 可能比两者都慢。| 写法 | 为什么慢 | 更好的做法 |
|---|---|---|
循环中 $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 个元素 | ms | 100,000 个元素 | ms | |
|---|---|---|---|---|
数组 += | 1446 | ForEach-Object { } | 181.5 | |
List[int].Add() | 297.7 | foreach ($x in $data) { } | 38.3 | |
$a = foreach (…) { $i } | 22.1 | $data.ForEach({ }) | 107.9 | |
字符串 += | 1046 | Where-Object { } | 265.0 | |
StringBuilder | 113.9 | $data.Where({ }) | 80.3 | |
对捕获的行 -join | 41.2 | foreach + if | 51.4 |
两个值得记住的意外:管道捕获($a = foreach …)在这里比 List[int].Add() 快 10 倍以上,因为每次 .Add() 都是从脚本发起的 .NET 方法调用,要经过绑定器开销,而 foreach 语句是原生收集输出;出于同样的原因,-join 也胜过了 StringBuilder。
Measure-Command 会丢弃脚本块的输出(好处是排除了格式化开销),并在当前作用域中运行(演示中 $x 被改成了 2)。对几百个对象,可读的管道完全没问题。当循环要处理几万个元素、函数在紧密循环中被调用,或分析(对脚本各部分用 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 已经修复了 +=” —— 最近的版本中它变快了,但仍是所测选项中最慢的。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' | 提供程序侧筛选 |
$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
$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
# 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 += $_ }
}
}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问题:一份覆盖 180,000 个 Azure 资源的夜间报表要跑 40 分钟。根因:循环里写的是 $report += [pscustomobject]@{…}。修复:$report = foreach ($r in $resources) { [pscustomobject]@{…} } —— 运行时间降到两分钟以内;瓶颈变成了 API 调用,这正是第 7 课的分页和 Resource Graph 能帮上忙的地方。
问题:Get-ChildItem \\fs\share -Recurse | Where-Object Extension -eq '.tmp' 要跑几个小时。修复:Get-ChildItem \\fs\share -Recurse -Filter *.tmp -File —— 由 SMB 服务器筛选,经过网络的条目少得多。
问题:{ Get-OpsServer } | Should-BeFasterThan 50ms 在共享运行器上时好时坏。修复:从单元测试中移除严格的计时断言;用单独的、重复多次的基准作业和宽松的预算跟踪性能。
原因:慢的是输出格式化或宿主(控制台渲染),而 Measure-Command 不包含这部分。修复:测量 { … | Out-Default },或把结果写入文件而不是控制台。
原因:对普通数组调用 .Add()。修复:创建 List[T],或使用管道捕获。
原因:返回集合时会被展开到管道中。修复:需要保留类型时用 return ,$list 或 Write-Output -NoEnumerate $list。
原因:.Where() 和 .ForEach() 返回 Collection[psobject]。它在索引和 .Count 方面与数组表现一致;如果某个 API 需要 object[],用 @(…) 转换。
Measure-Best 辅助函数,返回 N 次运行中最好的毫秒数。function Measure-Best([scriptblock]$Block, [int]$Repeat = 5) {
($(foreach ($i in 1..$Repeat) { (Measure-Command $Block).TotalMilliseconds }) | Measure-Object -Minimum).Minimum
}+= 改写 $out = @(); foreach ($s in Get-OpsServer) { if ($s.Monitored) { $out += $s.Name } }。$out = foreach ($s in Get-OpsServer) { if ($s.Monitored) { $s.Name } }Where-Object 都换成了 .Where()。你会批准吗?不会全盘批准。OpsKit 的集合很小(12 台服务器),可读性和流式处理比微秒级差距更重要。.Where() 需要完整集合都在内存中,并打断了管道的流式处理;Where-Object 适用于任何管道输入。只在经过测量的、处理大型内存集合的热点路径中批准,并要求拉取请求说明中附上基准数据。
Get-AuthenticodeSignature 检查签名,了解 Set-AuthenticodeSignature 如何用代码签名证书签署脚本,以及 AllSigned 和 RemoteSigned 的要求。ModuleVersion([version],不带标签)加 PrivateData.PSData.Prerelease;用 [semver] 比较版本;维护 CHANGELOG.md。.github/workflows/opskit.yml:Windows/Ubuntu/macOS 矩阵、shell: pwsh、固定工具版本、分析、测试、上传结果,并在打标签时用 API 密钥机密发布。| 层次 | 回答的问题 | 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 中。未签名时,它在那里会失败。
| 变更 | 升级 | OpsKit 示例 |
|---|---|---|
| 破坏性变更:删除/重命名函数或参数、改变输出类型 | MAJOR | 0.5.0 → 1.0.0(1.0 = “公共 API 从此稳定”) |
| 新增函数或可选参数 | MINOR | 1.0.0 → 1.1.0 新增 Get-OpsReport |
| 修复缺陷,API 不变 | PATCH | 1.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 记录面向用户的变更。
Bypass 就绕过了 App Control” —— 执行策略和 App Control 是两回事;CLM 无论如何都会被强制。③ “ModuleVersion = '1.0.0-rc1'” —— 无效;请用 Prerelease。④ “打标签就发布清单里的版本” —— 要检查标签与清单一致,否则会在 v1.0.0 标签下发布 0.5.0。⑤ “用仓库机密发布就行” —— 优先使用带必需审阅者的环境机密;来自分叉仓库的拉取请求工作流本来就拿不到机密。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.LanguageMode | FullLanguage / 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 |
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] 都被阻止。
# 仅限实验:自签名代码签名证书(生产环境请使用组织的 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 下不再能运行。在最后一次修改之后签名,作为构建的最后一步。
[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."
# 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.
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。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 需要经过签名并被策略允许。
./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'。问题:对一个已签名模块做了一行热修复后,所有服务器都报告 “is not digitally signed”。根因:工程师直接在服务器上编辑了文件;哈希不再匹配(HashMismatch)。修复:修复一律走流水线,签名是构建的最后一步,服务器只接收打好的包。
问题:用户请求“最新预发布版”,拿到的是 rc9,尽管 rc10 已经存在。根因:标签 rc9/rc10 按字符串比较(rc10 < rc9)。修复:使用 rc01…rc10,或在工具支持时使用点分的 rc.9/rc.10,并在打标签前用 [semver] 测试。
问题:某个步骤执行了 Write-Host "Publishing with key $key"。GitHub 会在日志中屏蔽已注册的机密,但变换过的值(例如 Base64)不会被屏蔽。修复:绝不打印机密;通过 env: 只传给需要它的那一个命令;一有怀疑就轮换。
原因:AllSigned(或 RemoteSigned 且文件带有 Zone.Identifier 标记)。修复:在构建中签名;对下载的文件在审阅后使用 Unblock-File。
原因:文件在签名后被修改(包括 Git 转换了换行符:在 .gitattributes 中为已签名文件设置 *.ps1 -text 或 eol=crlf)。
原因:ModuleVersion 中带了标签。修复:ModuleVersion = '1.0.0' 加 Prerelease = 'rc1'。
原因:已在 PSResourceGet 1.2.1 上验证:清单中有 Prerelease = ''。修复:删除空的 Prerelease 行(模块 8)。
原因:YAML 缩进错误,或未加引号的值中含有 : 。修复:在本地校验(“命令”页第 5 步),给表达式加引号,并保持 run: | 块缩进一致。
Get-ChildItem ./OpsKit -Recurse -Include *.ps1, *.psm1, *.psd1 | Get-AuthenticodeSignature |
Where-Object Status -ne 'Valid' | Select-Object Status, Path$m = Test-ModuleManifest ./OpsKit/OpsKit.psd1
$v = "$($m.Version)"; if ($m.PrivateData.PSData.Prerelease) { $v += "-$($m.PrivateData.PSData.Prerelease)" }
$v① 从内部 CA 获取代码签名证书(对外部用户则用公共 CA),存放在只有发布作业能访问的安全签名服务或 HSM 中。② 在 Package 的暂存步骤之后加一个 Sign 任务:为每个 .ps1/.psm1/.psd1 签名并加时间戳,然后再打包。③ 确保 Git 不会改变已签名文件的换行符。④ 请 App Control 负责人允许该发布者证书,让 OpsKit 运行在 FullLanguage 中。⑤ 增加一个测试:任何暂存文件不是 Valid 时失败。⑥ 只通过内部仓库分发。
没有找到讲解 Authenticode 签名或受限语言模式的已验证视频;请参考下面的文档。
Invoke-Formatter 让分析结果清零。Update-PSModuleManifest 升级到 1.0.0,并处理它在 Prerelease = '' 上的失败。build.ps1:快速失败(exit 1)、强制覆盖率、只暂存模块文件,并用 Compress-PSResource 生成 OpsKit.1.0.0.nupkg;发布到文件夹仓库。| 门禁 | 阈值 | OpsKit 1.0.0 结果(已验证) |
|---|---|---|
| 单元测试 | 在 Windows、Ubuntu、macOS 上全部通过 | 51 个通过,0 个失败(Windows 上运行;其他系统由工作流负责) |
| Public + Private 覆盖率 | ≥ 80%(由 build.ps1 强制) | 100% —— 9 个文件中 167/167 条命令 |
| PSScriptAnalyzer | 使用项目配置时 0 个 Error、0 个 Warning | 0 条(修复了 3 条花括号位置告警之后) |
| 清单 | ModuleVersion = '1.0.0'、有效、导出 = Public/*.ps1 | Test-ModuleManifest:1.0.0,7 个函数 |
| 包 | 只包含模块文件的 .nupkg | OpsKit.1.0.0.nupkg,10,808 字节,12 个文件 + nuspec |
| 文档 | 每个公有函数都有带示例的帮助;CHANGELOG | 由 OpsKit.Module.Tests.ps1 强制 |
如果 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.ps1 | 9 | TestDrive 测试数据、-ForEach、Should-All、经典 Should |
Get-OpsConfig.Tests.ps1 | 6 | Should-BeEquivalent、Should-Throw -ExceptionType/-ExceptionMessage |
Invoke-OpsBackup.Tests.ps1 | 7 | BeforeEach 隔离、Mock Get-Date、-WhatIf、Should-Invoke Remove-Item |
Test-OpsEndpoint.Tests.ps1 | 5 | Invoke-WebRequest 的默认 Mock + 过滤 Mock、管道输入 |
Invoke-OpsApi.Tests.ps1 | 6 | 重试序列、HttpResponseException、Mock Start-Sleep、Should-NotInvoke |
Invoke-OpsHealthCheck.Tests.ps1 | 3 | Mock 模块内部使用的公有函数、TestDrive 中的日志文件 |
Get-OpsCloudInventory.Tests.ps1 | 2 | 为未安装的命令建桩、Mock Get-Command |
Private.Tests.ps1 | 4 | InModuleScope -Parameters |
OpsKit.Module.Tests.ps1 | 9 | 清单、导出 = Public 目录、每个函数的帮助(发现阶段的 -ForEach) |
① 测试全绿且覆盖率 ≥ 80% → ② 分析清零 → ③ 写 CHANGELOG 条目 → ④ Update-PSModuleManifest -ModuleVersion 1.0.0 → ⑤ ./build.ps1 → ⑥ 从文件夹仓库安装 .nupkg 并做冒烟测试 → ⑦ 提交、打标签 v1.0.0、推送 → 工作流发布(模块 7)。
Monitored 解析后,51 个测试中只有 1 个失败,而且只是因为 Should-All 拒绝空集合(在“命令”页复现)。② “直接打包项目目录就行” —— 会把测试、构建脚本和 out/ 都发出去;只暂存模块文件。③ “Update-PSModuleManifest 只改版本号” —— 它会重新生成整个文件(注释、布局),并且在 1.2.1 中遇到空的 Prerelease 会失败。④ “VS Code 里分析通过了,CI 也会通过” —— CI 使用项目配置文件,花括号规则更严格;请在本地运行 ./build.ps1 -Task Analyze。⑤ “文件夹仓库需要服务器” —— 它就是一个放 .nupkg 的文件夹。日志是为本课录制的真实运行输出。
$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 | 对包做冒烟测试 |
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.
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
@{
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 重写了这三个文件。
@{
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。
<#
.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
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)。
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 采用它的原因。
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。费用:无。
~/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。out/repo 注册为文件夹仓库并安装;之后用 Unregister-PSResourceRepository OpsKitLocal 和 Uninstall-PSResource OpsKit 撤销。Remove-Item ./out -Recurse(只是构建输出,每次构建都会重新生成)。问题:一个团队把 Publish-Module -Path 指向仓库根目录来发布模块;包中包含了 tests/、一个 .env 文件和 out/。修复:像 build.ps1 那样暂存一个明确的允许列表(清单、根模块、Public、Private、CHANGELOG),在 CI 中检查 .nupkg 的内容,并轮换密钥。
问题:本地测试针对已安装的 OpsKit 0.5 通过了,而源码中有缺陷。根因:测试文件使用 Import-Module OpsKit(按名称导入)。修复:测试按路径导入("$PSScriptRoot/../OpsKit.psd1" -Force),与 OpsKit 的测试完全一样。
问题:一个发布拉取请求只改了版本号,却显示 130 行的清单 diff。根因:Update-PSModuleManifest 会重新生成文件。修复:一次性接受重新生成的布局(单独提交),或在 build.ps1 中用定点文本替换升级版本,再用 Test-ModuleManifest 校验。
阅读消息上方的表格;逐条修复或说明理由。Invoke-Formatter -Settings ./PSScriptAnalyzerSettings.psd1 可以修复布局类规则。
$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
原因:暂存目录名必须与清单名一致,且清单需要 Author 和 Description。修复:暂存到 out/stage/OpsKit;先运行 Test-ModuleManifest。
原因:文件名中的版本来自清单;有预发布标签时文件名是 OpsKit.1.0.0-rc1.nupkg。修复:根据 Version 和 Prerelease 构造期望的文件名。
out/ 的 Clean 任务。function Invoke-CleanTask {
Remove-Item -LiteralPath $out -Recurse -Force -ErrorAction Ignore
Write-Host 'Clean: removed out/.'
}
# 并把 'Clean' 加入 -Task 的 ValidateSet$zip = [System.IO.Compression.ZipFile]::OpenRead((Resolve-Path ./out/repo/OpsKit.1.0.0.nupkg)) $zip.Entries.FullName | Sort-Object; $zip.Dispose()
Get-OpsServer -Role api 不再返回 edge-01。这是缺陷吗?你应该发布什么版本?1.0.0 改变了角色解析(CHANGELOG:“Role as an array”,按逗号分割)。如果分号分隔的角色曾被文档化或被广泛使用,这就是回归:改为按 [,;] 分割,为两种分隔符都加测试用例,发布 1.0.1(PATCH:修复缺陷,API 不变)。如果从未支持过分号,就把格式写进文档,并考虑发布一个新增 -RoleSeparator 参数的 MINOR 版本。无论哪种情况,都先把出错的输入写成测试。
这些视频使用 PowerShellGet 的 Publish-Module;本课使用 PowerShell 7.6 自带的 PSResourceGet(Compress-PSResource、Publish-PSResource)。
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 -StrictInvoke-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 会被自动使用!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$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 -BeMock 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 = 报错$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(不含覆盖率)(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)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 的发布工程师。在打 v1.0.0 标签之前,你必须证明 build.ps1 在干净的代码树上通过,并且在以下情况下以退出码 1 和清晰的消息失败:(a) 某个函数被破坏,(b) 代码违反分析配置,(c) 测试缺失导致覆盖率低于 80%。不允许修改机器状态:一切都在 ~/pslab/OpsKit 中运行。
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
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,确认被破坏的版本现在会让两个测试失败。
catch 单独放一行,运行 ./build.ps1 -Task Analyze:预期出现一条 PSPlaceCloseBrace 告警和 exit=1(同模块 8 第 3 步)。用 Invoke-Formatter 修复。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 退出(已验证)。把文件移回去。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。
Measure-Command { 1..50 | ForEach-Object { Get-OpsServer -Path ~/pslab/data/servers.csv } } —— 记下耗时;以后有人报告 Get-OpsServer 慢时,这就是你的基线。Test-ModuleManifest ./OpsKit.psd1 报告 1.0.0,CHANGELOG 有 1.0.0 条目,.github/workflows/opskit.yml 能被解析,Get-AuthenticodeSignature 显示预期状态(实验中为 NotSigned)。发现阶段的初始化(资源管理器的运行方式可能掩盖了它,或在 Pester 5 语义下变量从别的文件泄漏过来;Pester 6 的按文件发现会把它暴露出来),或代理上的 Pester 版本不同(在 CI 日志中检查 Get-Module Pester)。把初始化移入 BeforeAll,并固定/导入 Pester ≥ 6。
在 Pester 6 中,不匹配任何过滤器且没有默认 Mock 的调用会抛错。默认 Mock 记录了“正常”的应答;带过滤器的 Mock 描述例外情况。
没有哪道门禁“失败”—— 测试根本没有断言那个出问题的行为。先用一个失败的测试复现,修复,发布 PATCH,并把该用例加入套件;考虑对具体值做断言,而不只检查形状/类型;如果崩溃涉及真实 I/O,再加一个集成测试。
Set-PSDebug -Trace 2 不安全?当代码处理机密时:! SET 行会把变量值打印到日志中。
| 主题 | 核实结果 | 来源(访问于 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) |
| PSScriptAnalyzer | 1.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.nupkg | Update-PSModuleManifest;Compress-PSResource;预发布版本;semver.org |
| GitHub Actions | actions/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 或视频工具使用。
Save-PSResource 保存到文件夹、通过 $env:PSModulePath 加载的,而不是安装的;路径被改写为 C:\Users\labadmin\pslab\…,TestDrive 临时路径改写为 …\AppData\Local\Temp\…,JUnit 示例中的主机名和用户名已替换。未在 Linux 或 macOS 上运行。Invoke-OpsHealthCheck 在这里是顺序执行的,Get-OpsCloudInventory 是对 Get-AzResource 的薄封装,只用 Mock 测试。