Visual: a script full of
Write-Host "x=$x" lines being deleted one by one; a red dot appears on line 6.Narration: stop guessing — stop the script where it goes wrong.
OpsKit: loose functions in Lesson 3 (v0.1), a real script module published to a local folder repository in Lesson 4 (v0.2), Invoke-OpsBackup with SupportsShouldProcess and a JSON log in Lesson 5 (v0.3), Invoke-OpsHealthCheck in Lesson 6 (v0.4), and Invoke-OpsApi plus Get-OpsCloudInventory in Lesson 7 (v0.5). Nothing so far proves that any of it works. This lesson adds the engineering discipline around the code — debugger, static analysis, unit tests with mocks, coverage, performance measurement, signing and a CI pipeline — and ends with the milestone OpsKit v1.0.0: 51 tests, 100% command coverage, zero analyzer findings, a build.ps1 and a .nupkg. Compare with Bash, where the equivalents are set -x, ShellCheck and bats.Write-Host: set line, command and variable breakpoints with Set-PSBreakpoint, drive the console debugger (s v o c k l), use Wait-Debugger, Set-PSDebug -Trace and the VS Code “Launch Current File” configuration.PSScriptAnalyzerSettings.psd1 (and know that a file with that name is picked up automatically), suppress a finding with a justification, and reformat code with Invoke-Formatter.Describe / Context / It, BeforeAll / BeforeEach, the new Should-* assertions and the classic Should -Be, TestDrive: and -ForEach data — and explain the discovery vs run phases that break naive test files.Invoke-WebRequest, Invoke-RestMethod, Get-Date, a native git) with -ModuleName and -ParameterFilter, assert calls with Should-Invoke, reach private functions with InModuleScope, and test -WhatIf and error paths.New-PesterConfiguration: JaCoCo coverage, NUnit/JUnit result files, and exit codes (Run.Exit, Run.Throw) — and know that a missed coverage target does not fail the run by itself.Measure-Command on array += vs List[T] vs pipeline capture, string += vs StringBuilder vs -join, Where-Object vs .Where(), and filter-left with -Filter.AllSigned, constrained language mode, SemVer with ModuleVersion + Prerelease, a CHANGELOG, and a GitHub Actions workflow that tests on Windows, Ubuntu and macOS and publishes on a tag.build.ps1 (Analyze, Test, Package) that fails fast with exit code 1, enforces an 80% coverage threshold and produces OpsKit.1.0.0.nupkg.| # | Time | Module | Core Content | Animation / Interactive | Lab (~/pslab) |
|---|---|---|---|---|---|
| 0 | Before Class | Prep | Pester 6.2.0 and PSScriptAnalyzer 1.25.0 side by side with the in-box Pester 3.4.0; VS Code PowerShell extension; OpsKit v0.5 layout | Self-check checklist | Load the right Pester; run a first test |
| 1 | 00–06 | Debugging | Set-PSBreakpoint (line, command, variable), debugger commands, $PSDebugContext, Wait-Debugger, Set-PSDebug -Trace / -Strict, Write-Debug, launch.json | Debugger stepper: s / v / o / c | Find the wrong total with breakpoints and actions |
| 2 | 06–13 | Static analysis | Invoke-ScriptAnalyzer, severities, settings file, auto-discovery, suppression, Invoke-Formatter, -Fix | Analyzer pipeline | Clean up a deliberately bad script |
| 3 | 13–21 | Pester basics | Describe / Context / It, BeforeAll / BeforeEach, discovery vs run, Should-* vs Should -Be, TestDrive, -ForEach | core animation: discovery and run phases | Tests for Get-OpsServer and Invoke-OpsBackup |
| 4 | 21–28 | Mocking | Mock -ModuleName -ParameterFilter, Should-Invoke, InModuleScope, testing -WhatIf and errors, native commands, REST retries | Mock resolver | Test Test-OpsEndpoint and Invoke-OpsApi without a network |
| 5 | 28–35 | Coverage and CI output | New-PesterConfiguration, CodeCoverage (JaCoCo), TestResult (NUnitXml / JUnitXml), Run.Exit, Run.Throw, -CI | From test run to CI status | Coverage report and result files for OpsKit |
| 6 | 35–42 | Performance | Measure-Command; += vs List[T] vs $x = foreach; StringBuilder; .Where(); foreach vs ForEach-Object; -Filter | Cost race | Benchmark six patterns on your machine |
| 7 | 42–50 | Security and release | Authenticode, AllSigned, constrained language mode, SemVer + Prerelease, CHANGELOG, GitHub Actions matrix and publish | Release pipeline | Write and validate .github/workflows/opskit.yml |
| 8 | 50–60 | OpsKit v1.0 | Test suite, analyzer clean-up, Update-PSModuleManifest, build.ps1, Compress-PSResource, local folder repository | build.ps1 gatekeeper + troubleshooting tree | Release OpsKit 1.0.0 |
| — | After Class | Cheat sheet · Integrated lab | Run build.ps1 end to end, break it on purpose, check the acceptance criteria | Final quiz (12 questions) | OpsKit.1.0.0.nupkg in out/repo |
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Debug interactively and unattended | ✓ | · | · | · | · | · | · | ✓ | Set-PSBreakpoint, Wait-Debugger, Set-PSDebug | M1 |
| Static analysis and formatting | · | ✓ | · | · | · | · | ✓ | ✓ | Invoke-ScriptAnalyzer, Invoke-Formatter | M2, M8 |
| Write Pester 6 tests | · | · | ✓ | ✓ | ✓ | · | · | ✓ | Describe, It, Should-Be, TestDrive | M3, M8 |
| Isolate dependencies with mocks | · | · | · | ✓ | · | · | · | ✓ | Mock, Should-Invoke, InModuleScope | M4, M8 |
| Coverage, reports and exit codes | · | · | · | · | ✓ | · | ✓ | ✓ | New-PesterConfiguration, Run.Exit | M5, integrated lab |
| Measure and fix performance | · | · | · | · | · | ✓ | · | · | Measure-Command, List[T], -Filter | M6 |
| Sign, version and document a release | · | · | · | · | · | · | ✓ | ✓ | Get-AuthenticodeSignature, [semver], Update-PSModuleManifest | M7, M8 |
| Automate build and CI | · | ✓ | · | · | ✓ | · | ✓ | ✓ | build.ps1, GitHub Actions, Compress-PSResource | M8, integrated lab |
| Topic | Why not in this lesson | Where to learn it |
|---|---|---|
Writing custom PSScriptAnalyzer rules, custom Should-* assertions (New-ShouldAssertion) | Useful for tool authors; the built-in rules and assertions cover OpsKit | PSScriptAnalyzer docs; Pester 6.1 release notes |
Pester's experimental parallel runner (Run.Parallel) | Marked experimental in 6.x; mocks and shared state need care | Pester 6.0 release notes |
| Integration tests against real cloud resources | Needs accounts and costs money; this lesson isolates them with mocks | Lesson 7, Azure and AWS courses |
| Code-signing certificates from a public CA, WDAC / App Control policies | Organization-level PKI and device policy; cannot be reproduced on a lab laptop | about_Signing, Microsoft App Control documentation |
| Azure DevOps / GitLab pipelines | Same ideas as GitHub Actions; one CI system is enough to learn the pattern | Git course and your CI's docs |
| Production incidents and interview questions across the whole course | Hour 9 collects them | Lesson 9 |
Should-* assertions, per-file discovery and run, profiler-based coverage, and removed Assert-MockCalled, the Pending status and mock fall-through. Pester 6 supports Windows PowerShell 5.1 and PowerShell 7.4+. PSScriptAnalyzer 1.25.0 (2026-03-20) was current. Windows still ships Pester 3.4.0 in C:\Program Files\WindowsPowerShell\Modules, which pwsh can see — Module 0 shows what happens when it gets loaded. All timings in Module 6 are from one machine and will differ on yours.SupportsShouldProcess). Lesson 7's Invoke-OpsApi is tested here with mocks, so no API or cloud account is needed.~/pslab/data (rebuild any time with ~/pslab/New-LabData.ps1).pwsh.[CmdletBinding(SupportsShouldProcess)] give a function, and what must the body call?The -WhatIf and -Confirm parameters; the body must wrap each change in if ($PSCmdlet.ShouldProcess($target, $action)) { … }. Module 4 tests exactly this.
The manifest's FunctionsToExport (and the root module's Export-ModuleMember). Private helpers stay inside the module — which is why tests need -ModuleName or InModuleScope (Module 4).
pwsh -File instead of -Command for automation?-File passes the script's exit N to the caller; -Command reports only 0 or 1. CI depends on exit codes (Modules 5 and 8).
The normal way is a current-user install with PSResourceGet (bundled with 7.6). Pin the versions you test with — CI will pin the same ones (Module 7):
Install-PSResource -Name Pester -Version 6.2.0 -Scope CurrentUser -TrustRepository Install-PSResource -Name PSScriptAnalyzer -Version 1.25.0 -Scope CurrentUser -TrustRepository
The lab machine for this lesson was not allowed to change user state, so the modules were saved into a folder instead and that folder was put first in $env:PSModulePath. This “vendored modules” approach is also handy on build agents:
$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 # this session only
Convention for this lesson: short demo scripts are saved as ~/pslab/lab/<name>.ps1 and run from ~/pslab with pwsh -NoProfile -File, which is why some error traces mention C:\Users\labadmin\pslab\lab\…. OpsKit lives in ~/pslab/OpsKit, Pester demo files in ~/pslab/demo and ~/pslab/gotcha.
Windows ships Pester 3.4.0 inside Windows PowerShell's module folder, and pwsh includes that folder in its module path. On a machine without a newer Pester, Import-Module Pester silently loads 3.4.0, and modern test files fail with confusing errors:
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” is the signature of Pester 3/4 running a Pester 5/6 file. With the new version first in the module path and a minimum version on the import:
$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
Always import with -MinimumVersion 6.0.0 (or put #Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.0.0' } at the top of a runner script). 41 commands match Should-* in 6.2.0 — the full list is in Module 3.
| Path | Contents |
|---|---|
~/pslab/OpsKit/OpsKit.psd1, OpsKit.psm1 | Manifest (v0.5.0) and root module that dot-sources Private/*.ps1 then Public/*.ps1 and exports only Public |
Public/ | Get-OpsServer, Get-OpsConfig, Test-OpsEndpoint, Invoke-OpsBackup, Invoke-OpsHealthCheck, Invoke-OpsApi, Get-OpsCloudInventory |
Private/ | Resolve-OpsPath (expands ~), Write-OpsLog (JSON lines to $env:OPSKIT_LOG) |
tests/ | Empty at v0.5 — Modules 3, 4 and 8 fill it |
The versions in this lesson are compact re-creations of what Lessons 3–7 built (same names and parameters, simplified bodies, Invoke-OpsHealthCheck sequential instead of parallel so it can be mocked). If your own OpsKit differs, the techniques apply unchanged. Every listing used in this lesson is shown in full in Module 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
Open ~/pslab/OpsKit in VS Code. The status bar must show PowerShell 7.6 (click the version to switch). The extension underlines PSScriptAnalyzer findings as you type and provides the debugger (Module 1). The Testing panel can run Pester tests through the Pester Tests extension; this lesson uses the command line so the outputs are reproducible.
TestDrive: (a temp folder deleted after each container) and to ~/pslab. Nothing is published to a real gallery and no certificate is created: the signing and publishing steps are shown as Expected output. To undo the prep: Uninstall-PSResource Pester, PSScriptAnalyzer -Version 6.2.0, 1.25.0 (if you installed them), or delete ~/pslab/modules. Leave the in-box Pester 3.4.0 alone; Windows components may use it.Set-PSBreakpoint, list and remove them, and attach an -Action that logs instead of stopping.s (step into), v (step over), o (step out), c (continue), k (call stack), l (list), q (quit), ? (help) — and evaluate any expression at the [DBG] prompt.Wait-Debugger, $PSDebugContext, Set-PSDebug -Trace 1/2 and -Strict, and Write-Debug with -Debug.[CmdletBinding()]). Importance:★★★★☆ (every later module is faster when you can stop and look)The debugger lives in the engine, not in an editor. Any host — the console, VS Code, a remote session — can stop a running script at a breakpoint, give you a nested [DBG] prompt in the script's scope, and resume. VS Code simply draws a UI on top of the same engine debugger.
| Breakpoint type | Set with | Stops when | Typical use |
|---|---|---|---|
| Line | Set-PSBreakpoint -Script f.ps1 -Line 6 (optional -Column) | That line is about to run | “What are the variables here?” |
| Command | Set-PSBreakpoint -Command Import-Csv | The command is called (wildcards allowed) | “Who calls Remove-Item, with what?” |
| Variable | Set-PSBreakpoint -Variable total -Mode Write (Read, ReadWrite) | The variable is written / read (verified: the action sees the value after the write) | “Who changes $total?” |
| In code | Wait-Debugger | Execution reaches the statement | Jobs, runspaces, remote sessions, code you cannot launch from an editor |
Write-Host "x=$x" lines must be added, removed again, and only show what you guessed in advance. A breakpoint lets you ask new questions at the moment of failure: $s | Format-List *, Get-PSCallStack, even call functions. A breakpoint with -Action is a non-invasive log line you add without editing the script. For unattended runs, Set-PSDebug -Trace prints every line executed — PowerShell's set -x.
| Key | Command | Effect | VS Code |
|---|---|---|---|
s | StepInto | Run one statement; enter functions and scripts it calls | F11 |
v | StepOver | Run one statement; calls run to completion | F10 |
o | StepOut | Finish the current function or script, stop in the caller | Shift+F11 |
c | Continue | Run until the next breakpoint | F5 |
q | Quit | Stop the script and leave the debugger | Shift+F5 |
k | Get-PSCallStack | Show the call stack | CALL STACK pane |
l / l 10 5 | List | Show source around the current line (* marks it) | Editor |
? / h | Help | List the commands | — |
| any expression | — | Evaluated in the script's scope: $s.Name, $total = 0 | DEBUG CONSOLE, VARIABLES, WATCH |
A single letter that is also a variable name ($s vs s) is fine because variables need the $. To print a variable literally named c you would type $c.
| Situation | Tool |
|---|---|
| Reproducible locally, in an editor | VS Code F9 breakpoint + F5 “Launch Current File” |
| Console only (server, SSH) | Set-PSBreakpoint then run the script |
| Want a log line without editing the file | Set-PSBreakpoint … -Action { Write-Host … } |
| Code runs in a job, runspace or another process | Wait-Debugger in the code, then Debug-Job, Debug-Runspace or Enter-PSHostProcess |
| Unattended (CI, scheduled task) | Set-PSDebug -Trace 1, Write-Verbose/Write-Debug, transcripts — never an interactive breakpoint |
| Typos in variable names | Set-StrictMode -Version Latest in the script (better than Set-PSDebug -Strict, see Commands) |
Set-PSBreakpoint works in any host. ② “Set-PSDebug -Strict catches every undefined variable” — it is strict mode version 1, which ignores variables inside strings (reproduced in Commands). ③ “A forgotten Wait-Debugger is harmless in production” — with an open stdin it waits forever; with stdin at end-of-file it is silently skipped (both verified on 7.6.10). ④ “-Debug asks for confirmation at every message” — that was Windows PowerShell 5.1; in 7.x it sets $DebugPreference = 'Continue' and just prints. ⑤ “Line breakpoints follow the code when I edit the file” — they are tied to a line number; editing above shifts them.Pick a scenario and step through it. The log shows the real console text from 7.6.10 sessions recorded for this lesson.
-Action, the action runs in the script's scope; unless the action calls break, execution continues. Otherwise the engine raises a debugger stop event and the host shows a nested prompt. Step commands set a one-shot condition (“stop at the next statement / at the next statement in this frame / when this frame returns”) and resume.| Command | Purpose | Notes |
|---|---|---|
Set-PSBreakpoint -Script f.ps1 -Line 6 | Line breakpoint | The script path must match the one you run (use a full path) |
Set-PSBreakpoint -Command Remove-* | Command breakpoint | Wildcards; add -Script to restrict to one file |
Set-PSBreakpoint -Variable total -Mode Write | Variable breakpoint | Name without $; modes Read, Write, ReadWrite |
-Action { … } | Run code instead of stopping | Call break inside to stop conditionally: -Action { if ($total -gt 3) { break } } |
Get-PSBreakpoint / Disable- / Enable- / Remove-PSBreakpoint | Manage the table | HitCount shows how often each fired |
Wait-Debugger | Stop here | Remove before committing (PSScriptAnalyzer has no rule for it — search for it in CI) |
$PSDebugContext | Exists only while stopped at [DBG] (it is $null inside an -Action) | .Breakpoints, .InvocationInfo; if ($PSDebugContext) = “am I in the debugger?” |
Set-PSDebug -Trace 1 / 2 / -Off | Line trace / plus assignments and calls | Output goes to the debug stream as DEBUG: lines |
Set-StrictMode -Version Latest | Fail on undefined variables, missing properties, bad calls | Scope-local; put it at the top of scripts and modules |
Write-Debug + -Debug | Developer messages | 7.x: -Debug sets $DebugPreference = 'Continue' (no prompts) |
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
How to verify: HitCount says the line breakpoint fired 6 times (6 prod servers) and the variable breakpoint 7 times (the initial $total = 0 plus 6 increments). Notice the action sees the value after the write. Common mistake: setting -Script ./x.ps1 and then running the file by another path — breakpoints match on the resolved full path. Production use: an action breakpoint is a safe way to instrument a script on a server without changing the file that is under change control.
$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
How to verify: after v on line 6, the debugger stops at line 4 (the foreach header) and $total is already 1. In the second session, s enters Get-Double, $n is 5, and o returns to the caller with $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
With stdin at end-of-file (pwsh -NonInteractive -File wait-demo.ps1 < /dev/null) the same script printed the debugger banner and then continued to prod: 6 in 0.7 s; with an open but silent stdin it waited until it was killed. Neither is what you want in production.
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 prints only the DEBUG: N+ >>>> … line markers; -Trace 2 adds ! CALL and ! SET. On Get-ProdSummary.ps1, -Trace 1 produced 37 trace lines for 12 servers — fine for a short script, overwhelming for a module.
$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.
How to verify: the reference inside the string ("in a string: $servers") passed silently — -Strict equals strict mode 1.0, which exempts strings. Set-StrictMode -Version Latest also catches that and non-existent properties. Production use: Set-StrictMode -Version Latest at the top of every script and in the module's .psm1.
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"
}
]
}
The three configuration shapes come from the snippets in the PowerShell extension's package.json (2026.1.2): “Launch Current File” uses ${file}, “Launch Script” accepts a path or a command (used here for Invoke-Pester), and “Attach” picks a running pwsh process. F9 toggles a breakpoint; right-click it for a condition or hit count.
Goal: find why a “count prod servers” script reports the wrong number, using breakpoints only. Environment: pwsh 7.6, ~/pslab/data/servers.csv. Cost: none.
-like 'prod*' on the wrong column:
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
You will see dev and staging servers in the list — the condition is wrong, not the counter.
$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
# at [DBG]: type $s | Format-List * then qSet-PSDebug -Trace 1; ./scripts/buggy.ps1; Set-PSDebug -Off — count how many DEBUG: lines appear. Then fix line 4 to if ($s.Env -eq 'prod') and confirm prod servers: 6.buggy.ps1, click in the gutter of line 4 (F9), press F5 and choose “PowerShell: Launch Current File”. Add $s.Env to WATCH and press F5 repeatedly.Get-PSBreakpoint | Remove-PSBreakpoint; Set-PSDebug -Off; Remove-Item ./scripts/buggy.ps1Problem: after an urgent fix, a scheduled OpsKit backup never finished. Root cause: the engineer had left Wait-Debugger in the script while diagnosing; the task's stdin was an open handle, so the debugger waited forever. Fix: remove it, add a CI check Select-String -Path ./**/*.ps1 -Pattern 'Wait-Debugger|Set-PSBreakpoint' that fails the build, and run scheduled tasks with a time limit.
Problem: $script:retryCount in a module was sometimes 0 when it should have been 3. Root cause: a helper assigned $retryCount = 0 (a new local variable) in one place and $script:retryCount in another. Fix found by: Set-PSBreakpoint -Variable retryCount -Mode Write -Action { Get-PSCallStack | Select-Object -First 2 | Out-String | Write-Host } showed both writers. Lesson 3's scope rules, seen live.
Problem: to debug a flaky pipeline, someone added Set-PSDebug -Trace 2. Root cause: ! SET $token = 'eyJ…' lines went to the public log. Fix: never trace in CI on code that handles secrets; use Write-Verbose with deliberate, redacted messages, and rotate the leaked token.
Cause: the script was run through a different path (relative vs full, symlink, a copy), or the line has no executable statement (a brace, a comment).
Get-PSBreakpoint | Format-Table Id, Script, Line, HitCount Set-PSBreakpoint -Script (Resolve-Path ./x.ps1).Path -Line 12
Cause (verified on 7.6.10): the action script block belongs to the session state where you created it (your console or script), so it cannot see the locals of a function running inside a module. A breakpoint on line 32 of OpsKit's Get-OpsServer printed Monitored='' -> for every row, while a plain breakpoint's [DBG] prompt showed $row.Name = web-01. Fix: stop interactively, or log from inside the function with Write-Debug.
Cause: a command breakpoint (-Command Get-*) matches everywhere. Fix: add -Script to restrict it, or use v (step over) instead of s.
Cause: the extension is attached to 5.1 or failed to start. Fix: click the version in the status bar, choose PowerShell 7.6, restart the session (Command Palette → “PowerShell: Restart Session”).
Cause: strict mode is on and the variable is misspelled or never assigned — exactly what strict mode is for. Fix: correct the name; for optional variables test with Test-Path Variable:x or initialize them.
Cause: the function lacks [CmdletBinding()], so -Debug is not a parameter, or $DebugPreference is SilentlyContinue. Fix: add [CmdletBinding()] and call with -Debug.
$total in Get-ProdSummary.ps1.$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 }
}The action runs in the script's scope, so keep your own counter in a scope you control (here $script: of the caller's script; at the console use $global:n).
Remove-Item call in a run and print its arguments, without stopping.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
Inside an -Action, $PSDebugContext is $null (verified) — it only exists at a real [DBG] stop. Get-PSCallStack works: frame 1 is the calling line.
Do not attach a debugger to the scheduled run. Capture evidence instead: run the task with Start-Transcript, -Verbose and, temporarily, a breakpoint with an -Action that logs the inputs of Test-OpsEndpoint (or Set-PSDebug -Trace 1 if no secrets are involved). Then reproduce the same conditions locally: same account (runas), pwsh -NoProfile -NonInteractive -File, same proxy/DNS. Typical root causes: the service account has no proxy settings, a relative path resolves to System32, or a module from the profile is missing (Lesson 1).
These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.
Write-Host "x=$x" lines being deleted one by one; a red dot appears on line 6.Invoke-ScriptAnalyzer on a file, a folder (-Recurse) or a string (-ScriptDefinition) and read RuleName, Severity, Line.PSScriptAnalyzerSettings.psd1 — and know that a file with exactly that name next to the analyzed path is used automatically and overrides -Severity.[Diagnostics.CodeAnalysis.SuppressMessageAttribute()] and a justification; fix layout with Invoke-Formatter and aliases with -Fix.PSScriptAnalyzer (PSSA) parses a script into the same AST the engine uses, then runs each rule over it. Nothing is executed, so it is safe on untrusted code and fast enough to run on every keystroke — the VS Code extension does exactly that. Version 1.25.0 has 75 rules: 8 Error, 56 Warning, 11 Information (counted with Get-ScriptAnalyzerRule on the lab machine).
| Rule (examples) | Severity | Why it matters |
|---|---|---|
PSAvoidUsingConvertToSecureStringWithPlainText | Error | The secret is in the script or the history |
PSAvoidUsingPlainTextForPassword | Warning | A [string]$Password parameter: use [securestring] or [pscredential] |
PSAvoidUsingCmdletAliases | Warning | gci, %: unreadable, and differ across platforms (Lesson 1) |
PSAvoidUsingWriteHost | Warning | Not capturable data (exempt in functions with the Show verb) |
PSUseApprovedVerbs | Warning | Fetch-Servers → Get-OpsServer; modules warn on import |
PSAvoidUsingEmptyCatchBlock | Warning | Swallowed errors (Lesson 5) |
PSPossibleIncorrectComparisonWithNull | Warning | $rows -eq $null filters an array; write $null -eq $rows |
PSUseDeclaredVarsMoreThanAssignments | Warning | Assigned, never used: dead code or a typo |
PSUseShouldProcessForStateChangingFunctions | Warning | Set-/Remove-/New- functions without SupportsShouldProcess |
PSAvoidUsingPositionalParameters | Information | Only for known commands with 3 or more positional arguments (verified) |
Every finding above is a bug or a review comment you no longer have to make by hand. In CI, PSSA becomes a gate: “no Errors or Warnings in module code”. It also enforces formatting (brace placement, indentation, casing) so diffs show logic, not whitespace.
| Setting | Meaning |
|---|---|
Severity = @('Error','Warning') | Report only these severities |
IncludeRules / ExcludeRules | Allow-list / deny-list rule names (wildcards) |
IncludeDefaultRules = $true | Keep the default set when you also configure extra rules |
Rules = @{ PSPlaceOpenBrace = @{ Enable = $true; OnSameLine = $true } } | Turn on configurable rules (formatting, PSUseCompatibleSyntax, PSUseCompatibleCommands) |
| Built-in presets | -Settings PSGallery, CodeFormatting, CodeFormattingOTBS, CodeFormattingStroustrup, CodeFormattingAllman |
Editor: the VS Code extension runs PSSA live (and reads a settings path from powershell.scriptAnalysis.settingsPath). Before commit: Invoke-ScriptAnalyzer -Path . -Recurse. In CI: the Analyze task of build.ps1 fails the build (Module 8). Suppress only with a written justification — the suppression is code-reviewed like anything else.
-Severity Error always limits the output to errors” — not if a PSScriptAnalyzerSettings.psd1 sits next to the analyzed path: it was picked up automatically and its Severity won (1 vs 10 findings, verified). ② “No findings means the code works” — PSSA checks style and known anti-patterns, not behavior; that is Pester's job. ③ “Write-Host is always flagged” — functions with the Show verb are exempt (verified). ④ “Positional parameters are always flagged” — only with three or more positional arguments to a command PSSA can resolve. ⑤ “Suppression hides problems” — a suppression with a justification documents a deliberate decision; use -IncludeSuppressed to audit them.Each scenario follows one run of Invoke-ScriptAnalyzer on scripts/bad.ps1; the log shows the real result counts from 7.6.10.
Invoke-ScriptAnalyzer resolves settings first (explicit -Settings, else a PSScriptAnalyzerSettings.psd1 found for the analyzed path), builds the rule set, parses the file, runs each rule to produce DiagnosticRecord objects, drops records filtered by severity or covered by a SuppressMessageAttribute, and writes the rest to the pipeline.| Command | Purpose | Notes |
|---|---|---|
Invoke-ScriptAnalyzer -Path x.ps1 | Analyze a file | -Recurse for folders |
Invoke-ScriptAnalyzer -ScriptDefinition $code | Analyze a string | Good for quick experiments |
-Severity Error, Warning | Filter | Overridden by a settings file's Severity |
-IncludeRule / -ExcludeRule | Pick rules | Wildcards allowed |
-Settings ./PSScriptAnalyzerSettings.psd1 | Use a settings file or preset name | Commit it to the repository |
-Fix | Apply suggested corrections in place | Rewrites the file: commit first |
-IncludeSuppressed | Show suppressed records too | IsSuppressed column |
Get-ScriptAnalyzerRule | List rules | -Name, -Severity |
Invoke-Formatter -ScriptDefinition $code -Settings … | Reformat text | Returns a string |
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
How to verify: line 13 (Fetch-Servers ./data 'P@ssw0rd!', two positional arguments to an unknown function) is not flagged, line 14 (Join-Path with three) is. Line 3 has both an Error (plaintext ConvertTo-SecureString) and a Warning ($secure never used). Common mistake: treating Information as noise forever; Production use: gate CI on Error + Warning, review Information occasionally.
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
How to verify: the same -Severity Error call returned 1 record without the file and 10 with a PSScriptAnalyzerSettings.psd1 next to the script — the file's Severity = Error, Warning replaced the parameter. With explicit -Settings, PSUseSingularNouns disappeared (excluded) and the Information record too (severity filter). Production use: keep one settings file at the repository root and always pass -Settings explicitly in CI so behavior never depends on the current folder.
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
The attribute sits on the function, before [CmdletBinding()], and applies to that function only. The second argument ('') can name a specific RuleSuppressionID; -Scope Function -Target 'Name*' forms exist for file-level suppression.
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 replaced gci and % with Get-ChildItem and ForEach-Object in the copy; positional arguments and the empty catch need a human. The last line is the CI-style count: -Severity Error with no settings file nearby gives 1.
Goal: take scripts/bad.ps1 to zero Errors and Warnings. Environment: pwsh 7.6, PSScriptAnalyzer 1.25.0. Cost: none.
Invoke-ScriptAnalyzer ./scripts/bad.ps1 | Sort-Object Line | Format-Table Line, Severity, RuleName and count the records (12 with no settings file).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 and compare.Remove-Item ./scripts/good.ps1Problem: developers ran Invoke-ScriptAnalyzer -Path ./src -Recurse -Severity Error and saw nothing; CI failed on Warnings. Root cause: CI ran from the repository root, where a PSScriptAnalyzerSettings.psd1 (Severity Error, Warning) was picked up; locally, people ran it from src. Fix: one settings file, always passed with -Settings, in the build script that both developers and CI run.
Problem: a script with ConvertTo-SecureString 'Winter2026!' -AsPlainText -Force was merged and the password ended up in the Git history. Fix: rotate the secret, take it from SecretManagement or a CI secret (Lesson 7), and make PSSA Errors block pull requests. Removing the line in a later commit does not remove it from history.
Problem: a pull request changing one condition showed 400 changed lines because an editor re-indented the file. Fix: agree on a formatting preset (CodeFormattingOTBS or a settings file), run Invoke-Formatter once in a separate “formatting only” commit, then enforce the layout rules in CI.
Cause: the module is not installed for pwsh 7 (or only in a vendored folder not on PSModulePath).
Get-Module PSScriptAnalyzer -ListAvailable Install-PSResource PSScriptAnalyzer -Version 1.25.0 -Scope CurrentUser
Cause: the extension uses its own bundled PSSA version and its own settings path. Fix: set "powershell.scriptAnalysis.settingsPath": "PSScriptAnalyzerSettings.psd1" in .vscode/settings.json and compare (Get-Module PSScriptAnalyzer).Version.
Cause: wrong rule name (it must be the exact RuleName, e.g. PSAvoidUsingWriteHost), or the attribute is not on the function/param block that contains the finding.
Cause: compatibility rules (PSUseCompatibleCommands) load large profiles; analyzing node_modules or build output. Fix: analyze only source folders, enable compatibility rules only in 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)
① Commit a settings file. ② Run -Fix and Invoke-Formatter in dedicated mechanical commits (easy to review, easy to revert). ③ Gate CI on Errors immediately (usually few, and they are security-relevant). ④ Gate Warnings only on changed files in pull requests (git diff --name-only → Invoke-ScriptAnalyzer). ⑤ Track the total count weekly until it reaches zero, then gate everything. Suppressions need a justification in review.
BeforeAll, Describe, Context, It, BeforeEach, AfterEach, AfterAll.Describe runs during discovery, so its variables are gone when It runs.Should-* family (Should-Be, Should-BeString, Should-BeCollection, Should-BeEquivalent, Should-Throw, …) and know where it differs from the classic Should -Be.TestDrive: / $TestDrive, and generate tests from data with -ForEach and <Name> templates.| Keyword | Job | Runs in phase |
|---|---|---|
Describe 'Get-OpsServer' { } | Group tests for one unit (usually one function) | Body: Discovery |
Context 'with filters' { } | Sub-group for one situation; its own setup and TestDrive scope | Body: Discovery |
It 'returns 12 servers' { } | One test: arrange, act, assert | Registered at Discovery, body at Run |
BeforeAll { } / AfterAll { } | Once per block (or file, at top level): import the module, build fixtures | Run |
BeforeEach { } / AfterEach { } | Before/after every It in the block and its children: fresh state, mocks | Run |
BeforeDiscovery { } | Compute data that -ForEach needs | Discovery |
Pester 6.2 allows several BeforeAll/AfterAll/BeforeEach/AfterEach in one block (6.0 threw on duplicates; 6.2 runs them in order, teardowns in reverse — from the 6.2.0 release notes).
Pester first executes the file in Discovery mode: it runs Describe/Context bodies to build a tree of tests, but does not run It bodies or Before* blocks. That makes filtering (-TagFilter, -FullNameFilter), test counts and data-driven expansion possible before anything runs. Then the Run phase walks the tree, running setup, tests and teardown in their own scopes. Since Pester 6, discovery and run happen per file: file A is discovered and run before file B is discovered, so discovery-time side effects no longer leak between files.
The rule: everything a test needs at run time goes into BeforeAll/BeforeEach or the It itself. Only data for -ForEach belongs to discovery.
| Classic (Pester 4/5, still in 6) | New in Pester 6 | |
|---|---|---|
| Equality | $x | Should -Be 5 | $x | Should-Be 5 (type of -Expected drives the comparison) |
| Strings | Should -BeExactly, -BeLike, -Match | Should-BeString -CaseSensitive, -TrimWhitespace, -NormalizeLineEnding; Should-BeLikeString, Should-MatchString |
| Booleans / null | Should -BeTrue, -BeNullOrEmpty | Should-BeTrue, Should-BeFalse, Should-BeNull, Should-BeTruthy |
| Collections | Should -Contain, -HaveCount | Should-BeCollection (same items, any order), Should-ContainCollection, Should-All, Should-Any |
| Objects | — | Should-BeEquivalent (deep compare, property diff), -ExcludePath, -ExcludePathsNotOnExpected |
| Exceptions | { … } | Should -Throw -ExpectedMessage '…' | { … } | Should-Throw -ExceptionMessage '…' -ExceptionType ([…]) (message uses -like) |
| Mocks | Should -Invoke | Should-Invoke, Should-NotInvoke (Module 4) |
| Switch off old syntax | $config.Should.DisableV5 = $true makes Should -Be throw — useful once a suite is migrated | |
$TestDrive (also the TestDrive: PSDrive) is a temporary folder created per Describe/Context and deleted afterwards — use it for every file a test writes. -ForEach on It, Context or Describe takes an array of hashtables; each key becomes a variable and a <key> template in the name. In Pester 6 an empty or $null -ForEach fails discovery unless you add -AllowNullOrEmptyForEach (verified).
Expected [int] 12, but got [int] 0). ② “Should-BeCollection checks order” — it does not: 'web','api' | Should-BeCollection @('api','web') passed; compare -joined strings when order matters. ③ “Should-Be is just Should -Be without the space” — piped @() becomes $null, -Expected drives conversion, and the messages differ. ④ “TestDrive is cleared between It blocks” — it lives for the whole Describe/Context; create unique sub-folders in BeforeEach. ⑤ “Import-Module Pester gives me Pester 6” — not if 3.4.0 is first (Module 0).Choose a test file layout and watch which pass executes each part. Red marks where the test goes wrong; the log shows real Pester 6.2.0 output.
Invoke-Pester creates a container per file and dot-sources it with Pester's block functions in “discovery” mode: Describe/Context invoke their script blocks immediately to collect children, while It, BeforeAll and friends only store their script blocks. After filtering, the run phase invokes the stored script blocks in fresh child scopes of the container, which is why a variable assigned in a Describe body is not visible inside It, while one assigned in BeforeAll is.| Command | Purpose | Notes |
|---|---|---|
Invoke-Pester -Path ./tests -Output Detailed | Run tests with one line per test | -Output: None, Normal, Detailed, Diagnostic |
Invoke-Pester -FullNameFilter '*retries*' | Run matching tests only | Also -TagFilter, -ExcludeTagFilter ('None' = untagged) |
It 'x' -Tag 'slow', -Skip | Tag / skip a test | Set-ItResult -Skipped -Because '…' inside a test (no -Pending in 6) |
Get-Command -Module Pester -Name 'Should-*' | List the new assertions | 41 in 6.2.0 |
$TestDrive, TestDrive:\ | Temporary folder per block | Deleted after the block |
It '<Env>: <Count>' -ForEach @(@{Env='dev';Count=2}) | Data-driven tests | Keys become variables |
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
How to verify: the only difference is BeforeAll { } around the two setup lines. In the broken file $servers was $null at run time, and $null.Count is 0. Common mistake: “fixing” it by making the variable $global: — it hides the bug and leaks state into other files. Production use: a review rule “nothing executable outside 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
How to verify: both syntaxes accept '1' for 1 (the expected value's type drives the conversion). Should-BeString -CaseSensitive shows the index and a caret. @() | Should-Be 0 fails as $null — the pipeline unwraps an empty array; use Should-Be -Actual @() -Expected … or a collection assertion. The “collection order matters” test passed, which is the surprise explained next.
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
Three Pester 6 behaviors in one run: an empty -ForEach fails the file at discovery, a mock whose only -ParameterFilter does not match throws instead of calling the real command (Module 4), and Should.DisableV5 turns Should -Be into an error.
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
How to verify: the fixture CSV is written to $TestDrive in the file-level BeforeAll, so the test never depends on ~/pslab/data and runs the same in CI. The -ForEach test expanded into two named tests. Should-All fails on an empty collection — that property catches a real bug in Module 8.
Goal: write tests for Get-OpsConfig and Invoke-OpsBackup that use only TestDrive. Environment: Pester 6.2.0, OpsKit v0.5. Cost: none.
Should-BeEquivalent, and three error paths:
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), odd file names, rotation driven by -ForEach, and Get-Date mocked for a stable file name (mocking is Module 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
The “What if:” line is the real -WhatIf message printed by the host during the test — harmless, and proof that ShouldProcess was consulted.
'backup-{0}.zip' to 'bak-{0}.zip' in Invoke-OpsBackup.ps1, re-run, read which tests fail and why, then revert.Problem: a test suite passed for months while a function was broken. Root cause: the file imported the module at top level and assigned $expected in the Describe body; at run time $expected was $null, and the assertion $result | Should -Be $expected compared $null with $null. Fix: move setup into BeforeAll; add Should-NotBeNull guards for values the test depends on.
Problem: a Windows build agent printed “The BeforeAll command may only be used inside a Describe block.” Root cause: the image only had the in-box Pester. Fix: install a pinned version in the pipeline and import with -MinimumVersion 6.0.0 so the wrong version fails loudly.
Problem: backup tests failed only when run after other tests. Root cause: they shared one fixed path in $TestDrive and a previous test had left zips behind (TestDrive is per block, not per test). Fix: unique sub-folders in BeforeEach — exactly what the OpsKit backup tests do.
Cause: Pester 3/4 is loaded. Fix: Get-Module Pester; Remove-Module Pester; Import-Module Pester -MinimumVersion 6.0.0.
Cause: the variable was assigned during discovery. Fix: move it into BeforeAll or BeforeEach.
Cause: Pester 6 rejects an empty -ForEach (usually data computed at discovery that came back empty). Fix: compute it in BeforeDiscovery correctly, or add -AllowNullOrEmptyForEach if empty is legitimate.
Cause: Should.DisableV5 = $true in the configuration (or $PesterPreference). Fix: migrate the assertion, or set it back to $false.
Cause: the Pending status was removed in Pester 6. Fix: Set-ItResult -Skipped -Because '…' or -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 cases, and the whole suite became slow even when you filter to one unrelated test. Why, and what do you change?Top-level code and BeforeDiscovery run during discovery for every run of that file, even if the filter later excludes all its tests — the data must exist to build the tree. Options: generate fewer, representative cases (boundaries, odd values) instead of every row; move bulk validation into a single It that loops at run time; or tag the file and exclude it from fast local runs. Keep discovery cheap.
Both videos predate Pester 6: they use Should -Be, which still works. No verified video covering the Pester 6 Should-* family was found; use the Pester 6.0.0 release notes and this module.
-ParameterFilter, and know that in Pester 6 a call that matches no filter and has no default mock throws.-ModuleName OpsKit so a mock reaches calls made inside the module, and InModuleScope to call private functions.Should-Invoke / Should-NotInvoke (or classic Should -Invoke), with -Times, -Exactly and filters, and read the invocation history Pester prints on failure.-WhatIf, error paths (Should-Throw), retries (mocked Invoke-RestMethod + Start-Sleep), native commands (git) and commands that are not installed (Get-AzResource).Mock Invoke-WebRequest { … } defines, for the current block, a function-like stand-in with the same parameters as the real command. Because functions beat cmdlets in command precedence (Lesson 1), code that calls Invoke-WebRequest from the same scope gets the mock. Pester records each call with its bound parameters.
| Dependency | Problem in a unit test | Mock it as |
|---|---|---|
Invoke-WebRequest, Invoke-RestMethod | Network, slow, flaky, real side effects | Return [pscustomobject]@{ StatusCode = 503 } or throw an HttpResponseException |
Get-Date | Changes every run | { '20261124-101500' } |
Start-Sleep | Retry back-off makes tests slow | { } and count the calls |
Remove-Item, Restart-Service | Destructive | { } + Should-Invoke with a filter |
git, az, kubectl | Native tool not installed in CI, or needs credentials | Mock git { 'main' } (works for applications too) |
Get-AzResource | Module not installed on the runner | Define a stub function first, then mock it (Mock needs the command to exist) |
| Your code calls the dependency from… | Mock with |
|---|---|
| A function dot-sourced into the test (script, not module) | Mock X { } |
Inside module OpsKit (public or private function) | Mock X -ModuleName OpsKit { } — and Should-Invoke X -ModuleName OpsKit |
| You want to call a private function directly | InModuleScope OpsKit -Parameters @{ … } { Resolve-OpsPath … } |
Prefer testing through the public interface with -ModuleName; use InModuleScope sparingly (it couples tests to internals) and pass values in with -Parameters rather than relying on outer variables.
Several mocks for one command are allowed: the most recently defined mock whose -ParameterFilter matches wins; a mock without a filter is the default. In Pester 6, if no filter matches and there is no default, the call throws “No mock for command … matched the call” instead of silently calling the real command (verified) — so define a default mock first. Verify with Should-Invoke -Times N -Exactly; without -Exactly, -Times means “at least”. A failed Should-Invoke prints every recorded call, with [*] for those that matched the filter.
Mock Invoke-WebRequest mocks it everywhere” — not inside a module without -ModuleName (reproduced: the real request ran and returned status 0). ② “A non-matching filter falls through to the real command” — removed in Pester 6; it throws. ③ “-ParameterFilter { $TimeoutSec -eq 2 } fails because the real parameter is -ConnectionTimeoutSeconds” — Pester 6 matches parameter aliases in filters (verified: the recorded call shows -ConnectionTimeoutSeconds 5, the filter on $TimeoutSec still worked). ④ “Testing -WhatIf needs a mock” — just check that nothing changed, and use a mock with Should-Invoke only for the destructive command. ⑤ “Mocks leak into the next test” — mocks defined in It or BeforeEach are removed after the test; mocks in BeforeAll live for the block.Each scenario follows one call from code under test to whatever answers it.
Mock generates a proxy function with the original command's parameter metadata and defines it in the target session state (the test scope, or the module's with -ModuleName). The proxy evaluates the registered behaviors newest-first: the first behavior whose -ParameterFilter returns true runs; otherwise the default behavior; otherwise, in Pester 6, an error. Every call is appended to a history that Should-Invoke later filters and counts.| Command | Purpose | Notes |
|---|---|---|
Mock Cmd { … } | Default replacement | Define in BeforeAll/BeforeEach/It |
Mock Cmd -ParameterFilter { $Name -eq 'x' } { … } | Conditional replacement | Variables are the command's parameters (aliases work) |
Mock Cmd -ModuleName OpsKit { … } | Mock calls made inside a module | Use the same -ModuleName on Should-Invoke |
Should-Invoke Cmd -Times 2 -Exactly -ModuleName OpsKit | Assert the call count | Classic: Should -Invoke Cmd -Times 2 -Exactly |
Should-NotInvoke Cmd -ModuleName OpsKit | Assert no call | Great for -WhatIf tests |
InModuleScope OpsKit -Parameters @{ P = 1 } { … } | Run code inside the module | Private functions and $script: variables |
New-MockObject -Type System.Diagnostics.Process | A fake .NET object of a type | When a parameter is strongly typed |
{ … } | Should-Throw -ExceptionMessage '*404*' -ExceptionType ([…]) | Error path | Wrap the call in a script block |
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
How to verify: test 1 really tried https://nowhere.invalid/ (the mock was in the wrong scope) and Test-OpsEndpoint returned status 0. Test 3 replaced git — a native application — and the classic Should -Invoke checked its arguments through $args. Test 4's failure lists both recorded calls, [*] for the one matching a.example.com; note how the [uri] argument is expanded and that the real parameter name is -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'
}
}
The default mock (no filter) is defined first; the two filtered mocks override it for specific hosts. A throw inside a mock body simulates a DNS failure.
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
How to verify: “retries a 503” asserts three calls to Invoke-RestMethod and two calls to Start-Sleep — the back-off ran but took no time. The helper New-HttpError builds the same HttpResponseException type that pwsh throws for HTTP errors, so $_.Exception.Response.StatusCode works in the code under test. Production use: every retry loop deserves these four tests: success, retry-then-success, non-retryable, give-up.
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*'
}
}
Mock Get-AzResource fails with “Could not find Command Get-AzResource” on a runner without Az, so the test first defines a stub with the one parameter the code uses. The second test mocks Get-Command itself — only for the name Get-AzResource — to exercise the “module missing” branch.
Goal: test Invoke-OpsHealthCheck without any network, and prove it logs unhealthy environments. Environment: Pester 6.2.0, OpsKit. Cost: none.
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 (a public OpsKit function called from inside the module, so -ModuleName OpsKit), point the log at TestDrive with $env:OPSKIT_LOG, and restore it in 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
-ModuleName OpsKit from the Mock and run again. The tests now call the real Test-OpsEndpoint, which tries dev.example.com — note how much slower and less deterministic that is, then restore it.$env:OPSKIT_LOG is removed in finally).Problem: running the test suite on a jump host restarted IIS. Root cause: Mock Restart-Service { } was declared without -ModuleName; the module's call went to the real cmdlet. Fix: -ModuleName on every mock of a call made inside a module, plus Should-Invoke … -ModuleName so a mock that is never hit makes the test fail. Run unit tests on build agents, not on servers.
Problem: retry tests took minutes. Root cause: real Start-Sleep with exponential back-off. Fix: Mock Start-Sleep -ModuleName OpsKit { } and assert the number of sleeps; keep one slow integration test with a tiny -RetryDelayMs if you need end-to-end proof.
Problem: after the upgrade, many tests failed with “No mock for command … matched the call”. Root cause: they relied on v5's fall-through to the real command when a filter did not match. Fix: add a default mock per command (often { }), which also makes the tests honest about every call they allow.
Cause: the call happened inside a module and the mock or the assertion lacks -ModuleName. Fix: add -ModuleName OpsKit to both.
Cause: Pester 6 removed fall-through. Fix: add a default Mock X { } before the filtered ones; the message lists the evaluated filters and bound parameters.
Cause: you cannot mock a command that does not exist. Fix: define a stub function (global, or in the module via InModuleScope) with the parameters you use, then mock it; remove it in AfterAll.
Cause: the script block runs in the module's scope. Fix: pass values with -Parameters @{ Path = $Path } (they become variables inside).
Cause: each runspace has its own session state. Fix: design the function so the parallel part is injectable (a -ThrottleLimit 1 / sequential path, or a script block parameter) and unit test the sequential path; cover the parallel path with an integration test.
Invoke-OpsBackup -Keep 1 never calls Remove-Item when there is only one backup.Mock Remove-Item -ModuleName OpsKit { }
$null = Invoke-OpsBackup -Source $source -Destination $destination -Keep 1
Should-NotInvoke Remove-Item -ModuleName OpsKitGet-Date inside OpsKit so it returns a fixed date only when called with -Format.Mock Get-Date -ModuleName OpsKit -ParameterFilter { $Format } { '20261124-101500' }
Mock Get-Date -ModuleName OpsKit { [datetime]'2026-11-24T10:15:00' } # default for other callsInvoke-OpsApi by starting a local HttpListener in BeforeAll. Another wants mocks only. What do you recommend?Both, at different levels. Unit tests with mocks prove the logic (retry rules, body serialization, -WhatIf) in milliseconds and never flake. One or two integration tests against the Lesson 7 mock API on 127.0.0.1 prove the real HTTP plumbing (headers, JSON parsing, exception types). Tag the integration tests (-Tag Integration) so CI can run them in a separate job and developers can exclude them locally.
Both predate Pester 6 (no Should-Invoke, and fall-through still existed). No verified video covering Pester 6 mocking changes was found.
New-PesterConfiguration: Run.Path, Run.PassThru, Output.Verbosity, CodeCoverage.*, TestResult.*.CoveragePercent and the missed commands.Run.Exit (exit code = number of failed tests), Run.Throw, and -CI — and know that a coverage target below the threshold does not fail the run by itself.New-PesterConfiguration returns a [PesterConfiguration] with sections; each option has a .Value, a .Default and a .Description. The simple parameter set of Invoke-Pester (-Path -Output -CI -PassThru) covers quick runs; CI uses the object.
| Section.Option | Use | Default |
|---|---|---|
Run.Path, Run.ExcludePath | Test files/folders | . |
Run.PassThru | Return the result object | $false |
Run.Exit | Exit the process with a non-zero code when tests fail | $false |
Run.Throw | Throw when tests fail (preferred over Exit when both are set) | $false |
Output.Verbosity | None, Normal, Detailed, Diagnostic | Normal |
Output.CIFormat | Auto, AzureDevops, GithubActions (error annotations) | Auto |
CodeCoverage.Enabled / Path / OutputFormat / OutputPath | Coverage of these files, as JaCoCo or Cobertura | off; JaCoCo; coverage.xml |
CodeCoverage.CoveragePercentTarget | Target shown in the summary | 75 |
CodeCoverage.UseBreakpoints | Old breakpoint-based coverage | $false (profiler-based since 6.0) |
TestResult.Enabled / OutputFormat / OutputPath | NUnitXml, NUnit2.5, NUnit3, JUnitXml | off; NUnitXml; testResults.xml |
Should.DisableV5 | Forbid Should -Be | $false |
The exit code makes the step red or green. The test-result file lets the CI system show test names, failures and trends. The coverage file shows which lines no test executed. Missing any one of them is a common reason for “CI is green but the tests failed”.
Pester counts commands (statements) in the files you list in CodeCoverage.Path and records which ones ran during the tests. Since Pester 6 this uses the profiler tracer instead of one breakpoint per command, which is much faster. CodeCoverage.ExcludeTests (on by default) keeps test files out of the numbers. 100% command coverage means every statement ran at least once — not that every branch combination or edge case was checked.
| Configuration | Tests fail → what happens | Verified |
|---|---|---|
| Nothing set | Summary printed, process exit code 0 | ✓ Result=Failed Failed=2, exit 0 |
Run.Exit = $true | exit with the number of failed tests | ✓ exit 2 for 2 failures; next line not reached |
Run.Throw = $true | Terminating error “Pester run failed, because 2 tests failed” | ✓ |
Invoke-Pester -CI | TestResult.Enabled + Run.Exit (coverage not included) | ✓ wrote testResults.xml, exit 2 |
Coverage below CoveragePercentTarget | Only reported: “Covered 29.34% / 80%”; exit 0 | ✓ — enforce it yourself (Module 8) |
pwsh -File run-tests.ps1 exits non-zero” — not unless you set Run.Exit/Run.Throw or check FailedCount yourself. ② “-CI turns on coverage” — not in Pester 6 (its help says so; enable CodeCoverage.Enabled). ③ “CoveragePercentTarget fails the build” — it only prints the target. ④ “100% coverage means no bugs” — Module 8's Should-All story shows a covered line with a wrong value; assertions matter more than percentages. ⑤ “Result files are harmless” — they include host name, user name, OS and working directory (seen in the JUnit file below); treat them as build artifacts, not public documents.Run.Throw it throws; with Run.Exit it calls exit with the failed-test count; otherwise it returns (and, per the option's description, still sets $LASTEXITCODE). The CI step's status comes from the process exit code of the pwsh that ran it.| Command | Purpose |
|---|---|
$c = New-PesterConfiguration | Start from defaults |
[PesterConfiguration]::Default.Run.Exit.Description | Read the built-in documentation of an option |
$r = Invoke-Pester -Configuration $c | Run (with Run.PassThru) |
$r.Result, $r.FailedCount, $r.Failed | Outcome, count, failed test objects |
$r.CodeCoverage.CoveragePercent, .CommandsMissed | Coverage numbers and missed statements (File, Line, Command) |
Invoke-Pester -CI | Shortcut: 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
How to verify: 167 commands in 9 covered files (7 public, 2 private), all executed. Common mistake: pointing CodeCoverage.Path at the whole project, so tests and build scripts dilute the number. Production use: publish both XML files as artifacts on every run, including failed ones (if: always() in Module 7).
<?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>
This file came from an earlier run with 48 tests (before Get-OpsCloudInventory's tests were added). JaCoCo paths are relative (Private/Resolve-OpsPath); Pester 6 makes coverage paths relative to Run.RepoRoot, found from the nearest .git folder.
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
Goal: a tests/run.ps1 that CI can call: results + coverage files, a non-zero exit code on failure or on low coverage. Environment: Pester 6.2.0. Cost: none.
#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 out of the folder and run with -Threshold 90. Every remaining test passes, but coverage drops and the script exits 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%
Note the summary still shows Pester's own default target (75%) because the script does not set CoveragePercentTarget; your threshold check is what decides. Losing one test file cost 14 points: the 6 Invoke-OpsApi tests were the only ones exercising its retry loop.
$r.CodeCoverage.CommandsMissed | Format-Table File, Line, Command (add Run.PassThru and keep $r).Remove-Item ./OpsKit/out -Recurse.Problem: a pipeline stayed green for two weeks while 3 tests failed. Root cause: the step ran pwsh -c "Invoke-Pester ./tests" — failures were printed, the exit code was 0. Fix: Run.Exit = $true (or -CI), plus a test-results file so the CI system shows failures prominently.
Problem: nobody deleted tests. Root cause: someone set CodeCoverage.Path = '.', which added build scripts and a vendored module to the denominator. Fix: list only the module's source folders, and keep ExcludeTests on.
Problem: an open-source project attached NUnit results to public releases. Root cause: result files include machine name, user and working directory. Fix: keep them as CI artifacts with retention, not release assets.
Cause: CodeCoverage.Path points to files that are not the ones the tests import (a copy in out/stage, a different module version from PSModulePath). Fix: import the module by path from the same folder you measure.
Cause: wrong format for the reporter (JUnit vs NUnit) or the file was not uploaded on failure. Fix: match TestResult.OutputFormat to the reporter; upload with if: always().
Cause: 6.2 validates values instead of silently ignoring them (release notes). Fix: read [PesterConfiguration]::Default.Section.Option.Description for the allowed values.
Cause: Pester 6 uses the profiler tracer by default. Fix: accept the new baseline, or set CodeCoverage.UseBreakpoints = $true temporarily to compare.
$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
No. Command coverage proves each statement ran, not that the tests checked the right results, nor that every branch combination and error path was exercised. OpsKit had 100% and still a real bug was caught only because Should-All fails on an empty collection (Module 8). Better goals: every public function has tests for its happy path, each documented error, -WhatIf, and boundary values; coverage is a smoke detector for untested code, not a quality score.
No verified video was found that covers Pester 6 configuration, coverage formats or exit codes specifically; use the Pester docs and this module's verified outputs.
Measure-Command correctly (warm-up, best of several runs, output discarded, scope effects).+=, List[T].Add() and pipeline capture ($a = foreach (…) { … }), and string +=, StringBuilder and -join.ForEach-Object vs foreach vs .ForEach(), and Where-Object vs .Where().-Filter at the provider beats Where-Object, and -Include can be slower than both.| Pattern | Why it costs | Better |
|---|---|---|
$a += $x in a loop | Arrays are fixed-size: each += allocates a new array and copies everything (O(n²)) | $a = foreach (…) { $x } or List[T] |
$s += "…" in a loop | Strings are immutable: each += copies the whole string | -join over a captured collection, or StringBuilder |
… | ForEach-Object { } on 100k items | Pipeline overhead + a script block invocation per item | foreach statement on data already in memory |
Get-ChildItem | Where-Object | Every file becomes an object first, then most are thrown away | -Filter (provider-side) |
Get-ChildItem -Include | Implemented as a post-filter with extra path handling | -Filter when one pattern is enough |
Real timings from 7.6.10 (best of 3, milliseconds; your numbers will differ, the ratios are what matter):
| 20,000 items | ms | 100,000 items | ms | |
|---|---|---|---|---|
array += | 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 | |
string += | 1046 | Where-Object { } | 265.0 | |
StringBuilder | 113.9 | $data.Where({ }) | 80.3 | |
-join over captured lines | 41.2 | foreach + if | 51.4 |
Two surprises worth remembering: pipeline capture ($a = foreach …) beat List[int].Add() by more than 10× here, because each .Add() is a .NET method call from script with binder overhead, while the foreach statement collects output natively; and -join beat StringBuilder for the same reason.
Measure-Command discards the script block's output (good: formatting cost is excluded) and runs it in the current scope ($x changed to 2 in the demo).Readable pipelines are fine for hundreds of objects. Reach for these patterns when a loop runs over tens of thousands of items, when a function is called in a tight loop, or when a profile (Measure-Command on parts of the script) shows where the time goes. In tests, Should-BeFasterThan can guard a budget, but timing assertions are flaky on shared CI runners — keep budgets generous.
List[T] is always the fastest way to build a collection” — capturing a foreach was 13× faster here; use List[T] when you add from several places or need .Remove(). ② “.Where() and Where-Object are the same” — .Where() needs the whole collection in memory but skips the pipeline (3.3× faster here). ③ “-Include is filter-left” — it was the slowest option (134 ms vs 64 ms for Where-Object and 4.4 ms for -Filter). ④ “Measure-Command shows my output” — it swallows it; use Measure-Command { … | Out-Default } to include display cost. ⑤ “7.x fixed +=” — it got faster in recent versions but is still the slowest option measured.foreach statement runs inside one compiled block, while ForEach-Object invokes a script block per input object through the pipeline processor. Method calls on .NET objects ($list.Add()) go through PowerShell's dynamic binder. Array += creates a new object[] each time.| Command / pattern | Use |
|---|---|
Measure-Command { … } | Returns a TimeSpan; output discarded |
(Measure-Command { … }).TotalMilliseconds | One number |
[Diagnostics.Stopwatch]::StartNew() | Time sections inside a script (OpsKit's Test-OpsEndpoint uses it) |
$list = [System.Collections.Generic.List[string]]::new() | Growable typed list |
$a = foreach ($x in $in) { f $x } | Fastest way to build an array from a loop |
[System.Text.StringBuilder]::new(), $null = $sb.Append() | Many string appends from different places |
$lines -join "`n" | Join once |
$data.Where({ … }, 'First', 5) | In-memory filter with modes (First, Last, Until, SkipUntil, Split) |
Get-ChildItem -Filter '*.log' | Provider-side filter |
$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
How to verify: all three variants return the same 200 files — always check the result count before comparing times. The last line proves Measure-Command runs in the current scope ($x became 2) and swallows output. Common mistake: timing a single run including first-time compilation. Production use: wrap suspected hot spots with a Stopwatch and log the milliseconds (Lesson 5's JSON log) before changing code.
Goal: speed up a log summarizer over access.log scaled to 61,100 lines. Environment: pwsh 7.6. Cost: a few MB in ~/pslab/tmp.
$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.logProblem: a nightly report over 180,000 Azure resources ran for 40 minutes. Root cause: $report += [pscustomobject]@{…} inside the loop. Fix: $report = foreach ($r in $resources) { [pscustomobject]@{…} } — the run dropped to under two minutes; the API calls became the bottleneck, which is where Lesson 7's paging and Resource Graph help.
Problem: Get-ChildItem \\fs\share -Recurse | Where-Object Extension -eq '.tmp' took hours. Fix: Get-ChildItem \\fs\share -Recurse -Filter *.tmp -File — the SMB server filters, so far fewer entries cross the network.
Problem: { Get-OpsServer } | Should-BeFasterThan 50ms failed on shared runners. Fix: remove strict timing assertions from unit tests; track performance with a separate, repeated benchmark job and generous budgets.
Cause: the slow part is output formatting or the host (console rendering), which Measure-Command excludes. Fix: measure { … | Out-Default }, or write results to a file instead of the console.
Cause: calling .Add() on a plain array. Fix: create a List[T], or use pipeline capture.
Cause: returning a collection unrolls it into the pipeline. Fix: return ,$list or Write-Output -NoEnumerate $list when the type matters.
Cause: .Where() and .ForEach() return Collection[psobject]. It behaves like an array for indexing and .Count; convert with @(…) if an API needs object[].
Measure-Best helper that returns the best of N runs in ms.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 } } without +=.$out = foreach ($s in Get-OpsServer) { if ($s.Monitored) { $s.Name } }Where-Object in OpsKit with .Where() “for performance”. Do you approve?Not wholesale. OpsKit's collections are tiny (12 servers), so readability and streaming matter more than microseconds. .Where() requires the full collection in memory and breaks streaming from a pipeline; Where-Object works on any pipeline input. Approve it only in measured hot paths over large in-memory collections, with a benchmark in the PR description.
Get-AuthenticodeSignature, know how Set-AuthenticodeSignature signs a script with a code-signing certificate, and what AllSigned and RemoteSigned require.ModuleVersion ([version], no label) plus PrivateData.PSData.Prerelease; compare versions with [semver]; keep a CHANGELOG.md..github/workflows/opskit.yml: a Windows/Ubuntu/macOS matrix with shell: pwsh, pinned tool versions, analyze, test, upload results, and publish on a tag with an API-key secret.| Layer | Question it answers | PowerShell mechanism |
|---|---|---|
| Integrity + origin | Was this file changed since X signed it? | Authenticode signature block at the end of .ps1/.psm1/.psd1; Get-AuthenticodeSignature → Valid, NotSigned, HashMismatch, NotTrusted |
| Policy | May this file run here? | Execution policy (AllSigned: every script signed by a trusted publisher; RemoteSigned: downloaded scripts signed) — a safety belt, not a boundary (Lesson 1) |
| Enforcement | What may untrusted code do? | App Control for Business (WDAC) / AppLocker put untrusted scripts into ConstrainedLanguage; trusted (allowed-signed) code runs in FullLanguage |
| Allowed in CLM | Blocked in CLM (verified on 7.6.10) |
|---|---|
Cmdlets and functions, the pipeline, core types ([string], [int], [hashtable], arrays) | Methods on non-core types: [System.IO.File]::ReadAllText() → “Method invocation is supported only on core types in this language mode.” |
| Loops, conditions, variables | Add-Type → “Definition of new types is not supported in this language mode.” |
| Modules allowed by the policy | [pscustomobject]@{…} → “Cannot convert value to type … Only core types are supported in this language mode.” |
OpsKit uses [pscustomobject], [System.IO.Compression.ZipFile] and [System.IO.Path]. That is fine as long as OpsKit is signed and allowed by the organization's App Control policy — then it runs in FullLanguage even on locked-down machines. Unsigned, it would fail there.
| Change | Bump | OpsKit example |
|---|---|---|
| Breaking: removed/renamed function or parameter, changed output type | MAJOR | 0.5.0 → 1.0.0 (1.0 = “public API is now stable”) |
| New function or optional parameter | MINOR | 1.0.0 → 1.1.0 adds Get-OpsReport |
| Bug fix, no API change | PATCH | 1.1.0 → 1.1.1 |
| Pre-release | label | ModuleVersion = '1.0.0' + Prerelease = 'rc1' → 1.0.0-rc1 |
ModuleVersion is a [version] (1.0.0-rc1 is rejected — verified); the label lives in PrivateData.PSData.Prerelease. PowerShell's [semver] type compares correctly: 1.0.0-rc1 < 1.0.0. Careful with labels: rc.2 < rc.10 (numeric identifiers), but rc2 < rc10 is False (string comparison) — use dotted labels or zero-padding. And never compare version strings: '1.10.0' -gt '1.9.0' is False.
On every push and pull request: analyze and test on all three operating systems. On a tag like v1.0.0: run the tests again, check the tag equals the manifest version, package, and publish with an API key stored as a GitHub environment secret (protected environment = a human approval before publishing). A CHANGELOG.md in Keep a Changelog format records what changed for users.
Bypass in CI disables App Control” — execution policy and App Control are separate; CLM is enforced regardless. ③ “ModuleVersion = '1.0.0-rc1'” — invalid; use Prerelease. ④ “A tag publishes whatever is in the manifest” — check that tag and manifest agree, or you publish 0.5.0 under a v1.0.0 tag. ⑤ “Repository secrets are fine for publishing” — prefer an environment secret with required reviewers; pull-request workflows from forks do not receive secrets anyway.on: filters to decide whether the workflow runs, expands the matrix into parallel jobs, and runs publish only when every needs job succeeded and its if: expression is true. With shell: pwsh, each run: block is saved to a temporary .ps1 and executed by pwsh; a non-zero $LASTEXITCODE or a terminating error fails the step.| Command | Purpose | Notes |
|---|---|---|
Get-AuthenticodeSignature ./x.ps1 | Signature status and signer | Read-only; works on any file type that supports Authenticode |
Set-AuthenticodeSignature -FilePath x.ps1 -Certificate $cert -TimestampServer http://timestamp.digicert.com | Sign | Needs a code-signing certificate; timestamp so the signature outlives the certificate |
Get-ExecutionPolicy -List | Effective policy per scope | Lesson 1 |
$ExecutionContext.SessionState.LanguageMode | FullLanguage / ConstrainedLanguage | Setting it to Constrained is one-way for the session |
[semver]'1.0.0-rc.1' | Parse/compare SemVer 2.0 | .PreReleaseLabel, .BuildLabel |
Update-PSModuleManifest -ModuleVersion 1.0.0 -Prerelease rc1 | Edit a manifest | PSResourceGet; rewrites the whole file |
Test-ModuleManifest ./OpsKit.psd1 | Validate and read a manifest | Throws on broken manifests |
Publish-PSResource -Path dir -Repository PSGallery -ApiKey $key | Publish | -DestinationPath also saves the .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.
How to verify: OpsKit is NotSigned; Microsoft's PSResourceGet manifest is Valid. The “You cannot run this script” text is the generic status message — with RemoteSigned and a local file it still runs. After switching the process to ConstrainedLanguage, cmdlets work, but .NET method calls, Add-Type and even [pscustomobject] are blocked.
# Lab only: a self-signed code-signing certificate (in production use your organization's 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.
Right after signing, Set-AuthenticodeSignature reports Valid, but verification shows the self-signed root is not trusted until the certificate is placed in Trusted Root and Trusted Publishers — which is exactly why a lab certificate must never be trusted machine-wide. Editing a signed file afterwards changes its hash: status HashMismatch, and under AllSigned it no longer runs. Sign after the last change, as the final build step.
[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
Validated without running GitHub: parsed with the powershell-yaml module and every run: block parsed as 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
How to verify: actions/checkout@v7 and actions/upload-artifact@v7 were the latest major releases on 2026-11-24 (GitHub API). Common mistake: forgetting if: always() on the upload step — then results disappear exactly when tests fail. Production use: pin third-party actions to a full commit SHA, keep permissions: contents: read, and put the API key in a protected environment. The workflow was not executed for this lesson.
Goal: prepare OpsKit's release metadata and CI workflow. Environment: pwsh 7.6, the OpsKit folder. Cost: none (nothing is pushed).
Get-ChildItem ./OpsKit -Recurse -Include *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Group-Object Status -NoElement and $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. …
The first failure is a .NET method call in the private helper, and the second error is its consequence — a typical CLM failure chain. On a CLM machine OpsKit would need to be signed and allowed by policy.
./OpsKit/.github/workflows/opskit.yml, then validate it: Install-PSResource powershell-yaml -Scope CurrentUser (or Save-PSResource) and run the validation script from Commands.[semver]'1.0.0-rc.9' -lt [semver]'1.0.0-rc.10' and [semver]'1.0.0-rc9' -lt [semver]'1.0.0-rc10'.Problem: after a one-line hotfix to a signed module, all servers reported “is not digitally signed”. Root cause: the engineer edited the file on a server; the hash no longer matched (HashMismatch). Fix: fixes go through the pipeline, signing is the last build step, and servers only receive packages.
Problem: users asked for the “latest prerelease” and got rc9 although rc10 existed. Root cause: labels rc9/rc10 compare as strings (rc10 < rc9). Fix: use rc01…rc10 or dotted rc.9/rc.10 where the tooling supports it, and test with [semver] before tagging.
Problem: a step ran Write-Host "Publishing with key $key". GitHub masks registered secrets in logs, but a transformed value (e.g. Base64) is not masked. Fix: never print secrets; pass them through env: to the one command that needs them; rotate on any suspicion.
Cause: AllSigned (or RemoteSigned with a Zone.Identifier mark). Fix: sign it in the build, or Unblock-File after review for downloaded files.
Cause: the file changed after signing (including line-ending conversion by Git: set *.ps1 -text or eol=crlf in .gitattributes for signed files).
Cause: a label in ModuleVersion. Fix: ModuleVersion = '1.0.0' and Prerelease = 'rc1'.
Cause: verified with PSResourceGet 1.2.1: the manifest contains Prerelease = ''. Fix: delete the empty Prerelease line (Module 8).
Cause: YAML indentation or an unquoted value containing : . Fix: validate locally (Commands step 5), quote expressions, and keep run: | blocks indented consistently.
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① Get a code-signing certificate from the internal CA (or a public CA for external users); store it in a secure signing service or HSM accessible to the release job only. ② Add a Sign task after Package's staging step: sign every .ps1/.psm1/.psd1 with a timestamp, then package. ③ Ensure Git does not alter line endings of signed files. ④ Ask the App Control owners to allow the publisher certificate, so OpsKit runs in FullLanguage. ⑤ Add a test that fails if any staged file is not Valid. ⑥ Distribute only through the internal repository.
No verified video on Authenticode signing or constrained language mode was found; use the documentation below.
Invoke-Formatter.Update-PSModuleManifest and handle its Prerelease = '' failure.build.ps1 that fails fast (exit 1), enforces coverage, stages only module files, and creates OpsKit.1.0.0.nupkg with Compress-PSResource; publish it to a folder repository.| Gate | Threshold | OpsKit 1.0.0 result (verified) |
|---|---|---|
| Unit tests | All pass on Windows, Ubuntu, macOS | 51 passed, 0 failed (Windows run; other OSes via the workflow) |
| Coverage of Public + Private | ≥ 80% (enforced by build.ps1) | 100% — 167 of 167 commands in 9 files |
| PSScriptAnalyzer | 0 Errors and 0 Warnings with the project settings | 0 findings (after fixing 3 brace-placement warnings) |
| Manifest | ModuleVersion = '1.0.0', valid, exports = Public/*.ps1 | Test-ModuleManifest: 1.0.0, 7 functions |
| Package | A .nupkg with only module files | OpsKit.1.0.0.nupkg, 10,808 bytes, 12 files + nuspec |
| Documentation | Help with an example for each public function; CHANGELOG | Enforced by OpsKit.Module.Tests.ps1 |
If CI runs commands that developers do not run, “works locally, fails in CI” is guaranteed. build.ps1 is the single entry point: developers run ./build.ps1 before pushing, and the workflow calls ./build.ps1 -Task Analyze and -Task Test. It sets $ErrorActionPreference = 'Stop' and Set-StrictMode -Version Latest, wraps the tasks in try/catch, and converts any failure into exit 1 (Lesson 1: run it with pwsh -File).
| File | Tests | Techniques |
|---|---|---|
Get-OpsServer.Tests.ps1 | 9 | TestDrive fixture, -ForEach, Should-All, classic Should |
Get-OpsConfig.Tests.ps1 | 6 | Should-BeEquivalent, Should-Throw -ExceptionType/-ExceptionMessage |
Invoke-OpsBackup.Tests.ps1 | 7 | BeforeEach isolation, Mock Get-Date, -WhatIf, Should-Invoke Remove-Item |
Test-OpsEndpoint.Tests.ps1 | 5 | Default + filtered mocks of Invoke-WebRequest, pipeline input |
Invoke-OpsApi.Tests.ps1 | 6 | Retry sequences, HttpResponseException, Mock Start-Sleep, Should-NotInvoke |
Invoke-OpsHealthCheck.Tests.ps1 | 3 | Mocking a public function used internally, log file in TestDrive |
Get-OpsCloudInventory.Tests.ps1 | 2 | Stub for a command that is not installed, mocking Get-Command |
Private.Tests.ps1 | 4 | InModuleScope -Parameters |
OpsKit.Module.Tests.ps1 | 9 | Manifest, exports = Public folder, help per function (-ForEach at discovery) |
① tests green and coverage ≥ 80% → ② analyzer clean → ③ CHANGELOG entry → ④ Update-PSModuleManifest -ModuleVersion 1.0.0 → ⑤ ./build.ps1 → ⑥ install the .nupkg from a folder repository and smoke-test it → ⑦ commit, tag v1.0.0, push → the workflow publishes (Module 7).
Monitored parsing failed only 1 of 51 tests, and only because Should-All refuses an empty collection (reproduced in Commands). ② “Packaging the project folder is fine” — it would ship tests, build scripts and out/; stage module files only. ③ “Update-PSModuleManifest only changes the version” — it regenerates the file (comments, layout) and in 1.2.1 fails on an empty Prerelease. ④ “The analyzer passed in VS Code, so CI will pass” — CI uses the project settings file with stricter brace rules; run ./build.ps1 -Task Analyze locally. ⑤ “A folder repository needs a server” — it is just a folder of .nupkg files.The logs are the real outputs of the runs recorded for this lesson.
$ErrorActionPreference = 'Stop' turns non-terminating errors inside them into exceptions too. The foreach over task names stops at the first exception, the catch prints one line and calls exit 1, which pwsh -File passes to the caller (Lesson 1).| Command | Purpose |
|---|---|
./build.ps1 / -Task Analyze, Test | Run all or selected tasks |
Update-PSModuleManifest -Path ./OpsKit.psd1 -ModuleVersion 1.0.0 | Bump the version |
Compress-PSResource -Path ./out/stage/OpsKit -DestinationPath ./out/repo | Create the .nupkg without publishing |
Register-PSResourceRepository -Name OpsKitLocal -Uri ~/pslab/OpsKit/out/repo -Trusted | Folder repository (Lesson 4) |
Install-PSResource OpsKit -Version 1.0.0 -Repository OpsKitLocal -Scope CurrentUser | Smoke-test the package |
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
The settings require } catch { on one line (PSPlaceCloseBrace NewLineAfter = $false); Invoke-Formatter with the same settings rewrote the three files.
@{
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.
The v0.5 manifest had Prerelease = ''. Remove that line, then bump again:
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
}
The new manifest above is shown without the ~110 comment lines that Update-PSModuleManifest generated. Note that VariablesToExport became a comment; review the diff before committing.
<#
.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
How to verify: with Monitored never true, “converts Monitored to a real boolean” still passed (it checks a false row and the type), but Get-OpsServer -MonitoredOnly | Should-All { … } received an empty collection and failed. Lesson: assert on concrete expected values (for example @(Get-OpsServer -MonitoredOnly).Count | Should-Be 3) in addition to properties of whatever comes back.
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
Alternative used for this lesson: Publish-PSResource -Path ./out/stage/OpsKit -Repository OpsKitLocal would also write the .nupkg into the folder; Compress-PSResource does it without any registered repository, which is why build.ps1 uses it.
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 and Invoke-OpsHealthCheck and their tests are listed in Module 4; Get-OpsServer, Get-OpsConfig and Invoke-OpsBackup tests in Module 3.
Goal: release OpsKit 1.0.0 on your machine. Environment: pwsh 7.6, Pester 6.2.0, PSScriptAnalyzer 1.25.0, PSResourceGet 1.2.x. Cost: none.
~/pslab/OpsKit/tests; Invoke-Pester ./tests → 51 passed.PSScriptAnalyzerSettings.psd1; run ./build.ps1 -Task Analyze; fix findings with Invoke-Formatter -Settings or by hand until “Analyze: 0 findings.”CHANGELOG.md; remove an empty Prerelease = '' if present; 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, and out/repo/OpsKit.1.0.0.nupkg.out/repo as a folder repository and install, as in Commands step 7; unregister afterwards with Unregister-PSResourceRepository OpsKitLocal and Uninstall-PSResource OpsKit.Remove-Item ./out -Recurse (build output only; it is recreated on every build).Problem: a team published their module by pointing Publish-Module -Path at the repository root; the package included tests/, a .env file and out/. Fix: stage an explicit allow-list (manifest, root module, Public, Private, CHANGELOG) as build.ps1 does, inspect the .nupkg contents in CI, and rotate the key.
Problem: tests passed locally against an installed OpsKit 0.5 while the source had a bug. Root cause: the test files used Import-Module OpsKit (by name). Fix: tests import by path ("$PSScriptRoot/../OpsKit.psd1" -Force), exactly like OpsKit's tests.
Problem: a release pull request showed a 130-line manifest diff for a version change. Root cause: Update-PSModuleManifest regenerates the file. Fix: accept the regenerated layout once (in its own commit), or bump with a targeted text replacement in build.ps1 and validate with Test-ModuleManifest.
Read the table above the message; fix or justify each finding. Invoke-Formatter -Settings ./PSScriptAnalyzerSettings.psd1 fixes layout rules.
$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
Cause: the staged folder name must match the manifest name, and the manifest needs Author and Description. Fix: stage to out/stage/OpsKit; run Test-ModuleManifest first.
Cause: the version in the file name comes from the manifest; with a prerelease the file is OpsKit.1.0.0-rc1.nupkg. Fix: build the expected name from Version and Prerelease.
Clean task to build.ps1 that removes out/.function Invoke-CleanTask {
Remove-Item -LiteralPath $out -Recurse -Force -ErrorAction Ignore
Write-Host 'Clean: removed out/.'
}
# and add 'Clean' to the ValidateSet of -Task$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 no longer returns edge-01 on their old CSV, where roles were separated by semicolons. Is this a bug, and what version do you ship?1.0.0 changed role parsing (CHANGELOG: “Role as an array”, split on commas). If semicolon-separated roles were documented or widely used, it is a regression: fix by splitting on [,;], add a test case for both separators, release 1.0.1 (PATCH: bug fix, no API change). If semicolons were never supported, document the format and consider a MINOR release adding a -RoleSeparator parameter. Either way, add the failing input as a test first.
These videos use PowerShellGet's Publish-Module; this lesson uses PSResourceGet (Compress-PSResource, Publish-PSResource), which ships with PowerShell 7.6.
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 into · v over · o out · c continue · k stack · l list · q quit · ? help
Wait-Debugger # never commit it
Set-PSDebug -Trace 1 # 2 = + SET/CALL; Set-PSDebug -Off
Set-StrictMode -Version Latest # better than 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 # rewrites the file
Invoke-Formatter -ScriptDefinition $code -Settings CodeFormattingOTBS
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'UI only')]
# a PSScriptAnalyzerSettings.psd1 next to -Path is used automatically!BeforeAll { Import-Module "$PSScriptRoot/../OpsKit.psd1" -Force } # NOT at top level
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 # not the in-box 3.4.0$x | Should-Be 5 # classic: $x | Should -Be 5
'a' | Should-BeString 'A' -CaseSensitive
$list | Should-BeCollection @(1, 2) # ANY order!
$obj | Should-BeEquivalent $expected -ExcludePath Id
$items | Should-All { $_.Ok } # fails on an empty collection
{ f } | Should-Throw -ExceptionMessage '*404*' -ExceptionType ([IO.FileNotFoundException])
Should-BeNull / Should-BeTrue / Should-HaveType / Should-BeHashtable
$c.Should.DisableV5 = $true # forbid Should -BeMock Invoke-WebRequest -ModuleName OpsKit { [pscustomobject]@{ StatusCode = 200 } } # default first
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' } # native commands too
function global:Get-AzResource { param($Tag) }; Mock Get-AzResource … # not installed
# Pester 6: no filter match + no default mock = error$c = New-PesterConfiguration
$c.Run.Path = './tests'; $c.Run.PassThru = $true
$c.Run.Exit = $true # exit code = failed count (or Run.Throw)
$c.CodeCoverage.Enabled = $true; $c.CodeCoverage.Path = './Public', './Private'
$c.CodeCoverage.OutputFormat = 'JaCoCo' # or Cobertura
$c.TestResult.Enabled = $true; $c.TestResult.OutputFormat = 'NUnitXml' # NUnit3, JUnitXml
$r = Invoke-Pester -Configuration $c
if ($r.CodeCoverage.CoveragePercent -lt 80) { exit 1 } # target alone does not fail
Invoke-Pester -CI # TestResult + Exit (no coverage)(Measure-Command { … }).TotalMilliseconds # warm up, best of N
$a = foreach ($i in $in) { f $i } # not $a += …
$l = [System.Collections.Generic.List[string]]::new(); $l.Add('x')
$lines -join "`n" # not $s += …
$sb = [System.Text.StringBuilder]::new(); $null = $sb.Append('x')
$data.Where({ $_ -gt 5 }) # in memory, no pipeline
Get-ChildItem -Filter *.log # filter left (not -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
You are the release engineer for OpsKit. Before tagging v1.0.0, you must show that build.ps1 passes on a clean tree and fails — with exit code 1 and a clear message — when (a) a function is broken, (b) code violates the analyzer settings, (c) tests are missing so coverage drops below 80%. You may not change machine state: everything runs in ~/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
-eq 'true' to -eq 'yes' in Get-OpsServer.ps1 and run only the Test task:
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
Then strengthen the suite: add @(Get-OpsServer -Path $csv -MonitoredOnly).Count | Should-Be 3 and confirm the broken version now fails two tests.
catch on its own line in one Public file, run ./build.ps1 -Task Analyze: expect a PSPlaceCloseBrace warning and exit=1 (as in Module 8 step 3). Fix with Invoke-Formatter.tests/Invoke-OpsApi.Tests.ps1 to ~/pslab/tmp and run ./build.ps1 -Task Test -CoverageThreshold 90: tests pass, coverage is 85.63%, the build prints “Test: coverage 85.63% is below the 90% threshold.” and exits 1. Move the file back.Set-PSBreakpoint -Script (Resolve-Path ./Public/Get-OpsServer.ps1).Path -Line 32 (the -MonitoredOnly check) and call Get-OpsServer -Path ~/pslab/data/servers.csv -MonitoredOnly. At the [DBG] prompt type $row.Monitored and $server.Monitored — the string is true but the boolean is False. Quit with q, remove the breakpoint and revert.
Use an interactive stop here, not an -Action: verified on 7.6.10, an action on a line inside a module function printed empty values for $row and $server (the action runs in the caller's session state, not the module's), while the [DBG] prompt showed web-01 and True on the clean module.
Measure-Command { 1..50 | ForEach-Object { Get-OpsServer -Path ~/pslab/data/servers.csv } } — note the time; this is your baseline if someone later reports Get-OpsServer as slow.Test-ModuleManifest ./OpsKit.psd1 reports 1.0.0, the CHANGELOG has a 1.0.0 entry, .github/workflows/opskit.yml parses, and Get-AuthenticodeSignature shows the expected state (NotSigned in the lab).Discovery-time setup (the explorer may run discovery and run in a way that hides it, or a variable leaked from another file in Pester 5 semantics; in Pester 6 per-file discovery exposes it), or a different Pester version on the agent (check Get-Module Pester in the CI log). Fix setup into BeforeAll and pin/import Pester ≥ 6.
In Pester 6 a call that matches no filter and has no default mock throws. The default mock documents the “normal” answer; filtered mocks describe the exceptions.
None of them “failed” — the tests did not assert the behavior that broke. Reproduce with a failing test first, fix, release a PATCH, and add the case to the suite; consider assertions on concrete values instead of only shape/type, and an integration test if the crash involved real I/O.
Set-PSDebug -Trace 2 unsafe?When the code handles secrets: ! SET lines print variable values into logs.
| Topic | Verified result | Sources (accessed 2026-11-24) |
|---|---|---|
| Pester versions | Gallery: Pester 6.2.0 (published 2026-09-09) current; 6.1.0 (2026-08-11), 6.0.0 (2026-07-07). Windows ships Pester 3.4.0 in C:\Program Files\WindowsPowerShell\Modules, visible to pwsh | Find-PSResource Pester; Pester 6.2.0 release |
| Pester 6 changes | Should-* assertions (41 commands in 6.2.0); per-file discovery and run; profiler coverage default, Cobertura, CoverageGutters removed; Assert-MockCalled, Pending, -Focus, mock fall-through removed; empty -ForEach throws; 6.2: several BeforeAll per block, config validation | 6.0.0 release notes; 6.1.0; 6.2.0; reproduced in this lesson |
| Pester behavior reproduced | Discovery-time variable is $null at run; Should-BeCollection ignores order; non-matching filtered mock throws; -ParameterFilter matches the TimeoutSec alias; Run.Exit exit code 2 for 2 failures; coverage target not enforced; -CI without coverage | Actual runs (outputs in Modules 3–5) |
| PSScriptAnalyzer | 1.25.0 (2026-03-20); 75 rules: 8 Error, 56 Warning, 11 Information; a PSScriptAnalyzerSettings.psd1 next to the analyzed path is applied automatically; Show-verb functions exempt from PSAvoidUsingWriteHost; positional rule needs 3+ arguments | Overview; Using PSScriptAnalyzer; actual runs |
| Debugger | Breakpoint types, debugger commands, Wait-Debugger, Set-PSDebug; $PSDebugContext is $null inside -Action, and an action cannot see locals of a module function; variable breakpoint action sees the written value; -Strict ignores variables in strings | about_Debuggers; Set-PSBreakpoint; Set-PSDebug; actual runs |
| VS Code launch configurations | “Launch Current File” (script: ${file}), “Launch Script”, “Attach to PowerShell Host Process” snippets in the extension's package.json, version 2026.1.2 | GitHub PowerShell/vscode-powershell package.json; Using VS Code |
| Performance | Timings in Module 6 from one Windows 11 machine (best of 3) | Performance considerations; actual runs |
| Signing and language modes | Get-AuthenticodeSignature on OpsKit (NotSigned) and PSResourceGet (Valid, Microsoft); CLM errors for method calls, Add-Type and [pscustomobject] | about_Signing; about_Language_Modes; actual runs |
| Versions and packaging | [version] rejects labels; [semver] ordering incl. rc2 vs rc10; PSResourceGet 1.2.1 Update-PSModuleManifest fails on Prerelease = ''; Compress-PSResource produced OpsKit.1.0.0.nupkg | Update-PSModuleManifest; Compress-PSResource; Prerelease versions; semver.org |
| GitHub Actions | actions/checkout v7.0.1 (2026-07-20) and actions/upload-artifact v7.0.2 (2026-10-07) latest; workflow YAML parsed with powershell-yaml 0.4.12 and each run: block parsed as PowerShell; not executed | GitHub REST API releases; Workflow syntax |
This lesson lists only videos whose titles and channels were checked via YouTube oEmbed on 2026-11-24:
oEmbed verifies titles and channels only; the videos were not watched segment by segment. All of them predate Pester 6 and most use PowerShellGet instead of PSResourceGet — where they differ, this lesson's verified outputs are authoritative. No verified video was found for Pester 6's Should-* assertions or mocking changes, Pester 6 coverage/exit-code configuration, Authenticode signing or constrained language mode.
The “Voice” tab uses the browser's built-in Web Speech API (en-US) to read the narration script; it needs no network access or external scripts. The courseware cannot embed MP3 files or generate video; the narration and storyboards can be passed to a TTS or video tool.
Save-PSResource) and loaded through $env:PSModulePath instead of installed; paths were rewritten to C:\Users\labadmin\pslab\…, TestDrive temp paths to …\AppData\Local\Temp\…, and host/user names in the JUnit sample were replaced. Not run on Linux or macOS.Invoke-OpsHealthCheck is sequential here, and Get-OpsCloudInventory is a thin wrapper over Get-AzResource tested only with mocks.