PowerShell Lesson 8: Testing, Debugging, Quality and Release

From “it works on my machine” to a release you can trust: find bugs with breakpoints instead of print statements, let PSScriptAnalyzer catch whole classes of mistakes, prove behavior with Pester 6 tests and mocks, measure coverage and speed, and ship OpsKit v1.0 through a build script and a GitHub Actions workflow
PowerShell 7.6 LTS (7.6.10)Pester 6.2.0PSScriptAnalyzer 1.25.0Local only · FreeVerified · 2026-11-24
Position in the Learning Path Lessons 1–7 built the language, tool-making and automation skills and grew the running project 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.
Overall Learning Objectives
  • Debug with breakpoints, not 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.
  • Run PSScriptAnalyzer, read rule severities, control it with 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.
  • Write Pester 6 tests with 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.
  • Mock dependencies (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.
  • Configure a CI run with 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 before optimizing: Measure-Command on array += vs List[T] vs pipeline capture, string += vs StringBuilder vs -join, Where-Object vs .Where(), and filter-left with -Filter.
  • Understand Authenticode signing, 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.
  • Release OpsKit v1.0.0 with a build.ps1 (Analyze, Test, Package) that fails fast with exit code 1, enforces an 80% coverage threshold and produces OpsKit.1.0.0.nupkg.

1-Hour Time Allocation

#TimeModuleCore ContentAnimation / InteractiveLab (~/pslab)
0Before ClassPrepPester 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 layoutSelf-check checklistLoad the right Pester; run a first test
100–06DebuggingSet-PSBreakpoint (line, command, variable), debugger commands, $PSDebugContext, Wait-Debugger, Set-PSDebug -Trace / -Strict, Write-Debug, launch.jsonDebugger stepper: s / v / o / cFind the wrong total with breakpoints and actions
206–13Static analysisInvoke-ScriptAnalyzer, severities, settings file, auto-discovery, suppression, Invoke-Formatter, -FixAnalyzer pipelineClean up a deliberately bad script
313–21Pester basicsDescribe / Context / It, BeforeAll / BeforeEach, discovery vs run, Should-* vs Should -Be, TestDrive, -ForEachcore animation: discovery and run phasesTests for Get-OpsServer and Invoke-OpsBackup
421–28MockingMock -ModuleName -ParameterFilter, Should-Invoke, InModuleScope, testing -WhatIf and errors, native commands, REST retriesMock resolverTest Test-OpsEndpoint and Invoke-OpsApi without a network
528–35Coverage and CI outputNew-PesterConfiguration, CodeCoverage (JaCoCo), TestResult (NUnitXml / JUnitXml), Run.Exit, Run.Throw, -CIFrom test run to CI statusCoverage report and result files for OpsKit
635–42PerformanceMeasure-Command; += vs List[T] vs $x = foreach; StringBuilder; .Where(); foreach vs ForEach-Object; -FilterCost raceBenchmark six patterns on your machine
742–50Security and releaseAuthenticode, AllSigned, constrained language mode, SemVer + Prerelease, CHANGELOG, GitHub Actions matrix and publishRelease pipelineWrite and validate .github/workflows/opskit.yml
850–60OpsKit v1.0Test suite, analyzer clean-up, Update-PSModuleManifest, build.ps1, Compress-PSResource, local folder repositorybuild.ps1 gatekeeper + troubleshooting treeRelease OpsKit 1.0.0
—After ClassCheat sheet · Integrated labRun build.ps1 end to end, break it on purpose, check the acceptance criteriaFinal quiz (12 questions)OpsKit.1.0.0.nupkg in out/repo

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLab
Debug interactively and unattended✓······✓Set-PSBreakpoint, Wait-Debugger, Set-PSDebugM1
Static analysis and formatting·✓····✓✓Invoke-ScriptAnalyzer, Invoke-FormatterM2, M8
Write Pester 6 tests··✓✓✓··✓Describe, It, Should-Be, TestDriveM3, M8
Isolate dependencies with mocks···✓···✓Mock, Should-Invoke, InModuleScopeM4, M8
Coverage, reports and exit codes····✓·✓✓New-PesterConfiguration, Run.ExitM5, integrated lab
Measure and fix performance·····✓··Measure-Command, List[T], -FilterM6
Sign, version and document a release······✓✓Get-AuthenticodeSignature, [semver], Update-PSModuleManifestM7, M8
Automate build and CI·✓··✓·✓✓build.ps1, GitHub Actions, Compress-PSResourceM8, integrated lab

Excluded from this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn it
Writing custom PSScriptAnalyzer rules, custom Should-* assertions (New-ShouldAssertion)Useful for tool authors; the built-in rules and assertions cover OpsKitPSScriptAnalyzer docs; Pester 6.1 release notes
Pester's experimental parallel runner (Run.Parallel)Marked experimental in 6.x; mocks and shared state need carePester 6.0 release notes
Integration tests against real cloud resourcesNeeds accounts and costs money; this lesson isolates them with mocksLesson 7, Azure and AWS courses
Code-signing certificates from a public CA, WDAC / App Control policiesOrganization-level PKI and device policy; cannot be reproduced on a lab laptopabout_Signing, Microsoft App Control documentation
Azure DevOps / GitLab pipelinesSame ideas as GitHub Actions; one CI system is enough to learn the patternGit course and your CI's docs
Production incidents and interview questions across the whole courseHour 9 collects themLesson 9

How to use these materials

10 pages per module
Principles · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. The Module 3 animation (discovery vs run) explains most “my test sees $null” problems — watch it before you write tests.
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress. Progress is saved in this browser's local storage (if the browser blocks local storage, it resets on refresh).
Voice narration
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the narration script. Without a voice pack the script can still be read, or passed to a TTS tool.
Version notes Verified 2026-11-24 on PowerShell 7.6.10 (.NET 10.0.15, Windows 11). Pester 6.2.0 (2026-09-09) was the current release on the PowerShell Gallery; Pester 6.0.0 shipped 2026-07-07 with the new 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.

Module 0 · Prep: Pester 6, PSScriptAnalyzer and the VS Code debugger

Get the current Pester and PSScriptAnalyzer next to the old in-box Pester, make sure the right one loads, and lay out OpsKit v0.5 for testing
Before class ≈ 10 minRuns locally · FreeWrites only inside ~/pslab
Prerequisites
  • Lessons 3–5 (advanced functions, modules, SupportsShouldProcess). Lesson 7's Invoke-OpsApi is tested here with mocks, so no API or cloud account is needed.
  • The dataset from Lesson 1 in ~/pslab/data (rebuild any time with ~/pslab/New-LabData.ps1).
  • VS Code with the PowerShell extension (2026.x) for the debugger part of Module 1. Everything else runs in a plain pwsh.

Warm-up: answer from memory (30 seconds)

1. In Lesson 5, what does [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.

2. In Lesson 4, which file decides what a module exports?

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).

3. Why did Lesson 1 insist on 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).

Step 1: install Pester 6 and PSScriptAnalyzer

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.

Step 2: the “wrong Pester” trap

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.

Step 3: the OpsKit v0.5 layout this lesson tests

PathContents
~/pslab/OpsKit/OpsKit.psd1, OpsKit.psm1Manifest (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

Step 4: VS Code

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.

Environment self-check checklist

Risks and cleanup Tests in this lesson write only to Pester's 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.

Module 1 · Debugging: breakpoints, the VS Code debugger, Set-PSDebug and Wait-Debugger

00:00 – 06:00 · Stop guessing with Write-Host: pause the script where the state goes wrong, look at the variables, step through the code, and keep a non-interactive trace for the cases where nobody can sit at a debugger
6 minSet-PSBreakpoint · Wait-Debugger★★★★☆
Learning objectives
  • Set line, command and variable breakpoints with Set-PSBreakpoint, list and remove them, and attach an -Action that logs instead of stopping.
  • Drive the console debugger: 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.
  • Use Wait-Debugger, $PSDebugContext, Set-PSDebug -Trace 1/2 and -Strict, and Write-Debug with -Debug.
  • Debug in VS Code with the “PowerShell: Launch Current File” configuration (F5, F9, F10, F11).
Prerequisites: Lesson 3 (functions, [CmdletBinding()]). Importance:★★★★☆ (every later module is faster when you can stop and look)

What: the PowerShell debugger is part of the engine

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 typeSet withStops whenTypical use
LineSet-PSBreakpoint -Script f.ps1 -Line 6 (optional -Column)That line is about to run“What are the variables here?”
CommandSet-PSBreakpoint -Command Import-CsvThe command is called (wildcards allowed)“Who calls Remove-Item, with what?”
VariableSet-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 codeWait-DebuggerExecution reaches the statementJobs, runspaces, remote sessions, code you cannot launch from an editor

Why: print debugging does not scale

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.

How: debugger commands at the [DBG] prompt

KeyCommandEffectVS Code
sStepIntoRun one statement; enter functions and scripts it callsF11
vStepOverRun one statement; calls run to completionF10
oStepOutFinish the current function or script, stop in the callerShift+F11
cContinueRun until the next breakpointF5
qQuitStop the script and leave the debuggerShift+F5
kGet-PSCallStackShow the call stackCALL STACK pane
l / l 10 5ListShow source around the current line (* marks it)Editor
? / hHelpList the commands—
any expression—Evaluated in the script's scope: $s.Name, $total = 0DEBUG 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.

When: which tool for which situation

SituationTool
Reproducible locally, in an editorVS Code F9 breakpoint + F5 “Launch Current File”
Console only (server, SSH)Set-PSBreakpoint then run the script
Want a log line without editing the fileSet-PSBreakpoint … -Action { Write-Host … }
Code runs in a job, runspace or another processWait-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 namesSet-StrictMode -Version Latest in the script (better than Set-PSDebug -Strict, see Commands)
Common misconceptions① “Breakpoints need VS Code” — they are engine features; 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.

Diagram: where a breakpoint puts you

Script runningGet-ProdSummary.ps1line 4 → 5 → 6in the script scope line 6 Breakpoint tableLine Get-ProdSummary.ps1:6Command Import-CsvVariable total (Write)-Action { … } ? run itno action / break → stop [DBG] nested prompt (same scope)$PSDebugContext.Breakpoints · InvocationInfo$s.Name · $total · Get-PSCallStack (k)l = list source · ? = helps / v / o = step · c = continue · q = quithost decides UI: console text or VS Code panes Non-interactive alternatives Set-PSDebug -Trace 1 (lines) / -Trace 2 (+ variable assignments and calls) · Write-Debug + -Debug · Write-Verbose + -Verbose Set-PSBreakpoint -Action { Write-Host … } — a log line without editing the script Wait-Debugger + Debug-Job / Debug-Runspace / Enter-PSHostProcess for code that runs elsewhere
Figure 1-1: the engine checks the breakpoint table before each statement; an action runs and continues, a plain breakpoint opens a nested prompt in the script's own scope

Diagram: step commands on a call

trace-demo.ps1 1 function Get-Double([int]$n) { $n * 2 } 2 $x = 5 3 $y = Get-Double $x ◀ breakpoint 4 "y=$y" s (step into)line 3 → inside Get-Double ({ then $n * 2) v (step over)line 3 → line 4 (Get-Double runs completely) o (step out, from inside Get-Double)→ back in the caller at line 4, $y = 10
Figure 1-2: the same three steps you see in the real session in the Commands tab (s, s, o)

Debugger stepper: what happens after each command?

Pick a scenario and step through it. The log shows the real console text from 7.6.10 sessions recorded for this lesson.

Ready.
Real mechanism behind the animation Before each statement the engine checks its breakpoint table (line, command, variable). If a breakpoint matches and has an -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 table

CommandPurposeNotes
Set-PSBreakpoint -Script f.ps1 -Line 6Line breakpointThe script path must match the one you run (use a full path)
Set-PSBreakpoint -Command Remove-*Command breakpointWildcards; add -Script to restrict to one file
Set-PSBreakpoint -Variable total -Mode WriteVariable breakpointName without $; modes Read, Write, ReadWrite
-Action { … }Run code instead of stoppingCall break inside to stop conditionally: -Action { if ($total -gt 3) { break } }
Get-PSBreakpoint / Disable- / Enable- / Remove-PSBreakpointManage the tableHitCount shows how often each fired
Wait-DebuggerStop hereRemove before committing (PSScriptAnalyzer has no rule for it — search for it in CI)
$PSDebugContextExists 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 / -OffLine trace / plus assignments and callsOutput goes to the debug stream as DEBUG: lines
Set-StrictMode -Version LatestFail on undefined variables, missing properties, bad callsScope-local; put it at the top of scripts and modules
Write-Debug + -DebugDeveloper messages7.x: -Debug sets $DebugPreference = 'Continue' (no prompts)

1. Breakpoints with actions: log without editing the script

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.

2. An interactive session (stdin scripted, real output)

$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.

3. Wait-Debugger

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

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

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

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

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.

4. Set-PSDebug -Trace: PowerShell's set -x

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

-Trace 1 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.

5. Set-PSDebug -Strict vs Set-StrictMode

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

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.

6. Write-Debug and -Debug

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

7. VS Code: .vscode/launch.json

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

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.

Create a buggy copy — it counts -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
Log every increment without editing the file:
$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.

Stop conditionally: stop only when a non-prod server is counted, then inspect it.
$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  q
Trace instead: Set-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.
VS Code: open 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.
Cleanup: Get-PSBreakpoint | Remove-PSBreakpoint; Set-PSDebug -Off; Remove-Item ./scripts/buggy.ps1

Case 1: a nightly job “hung” after a hotfix

Problem: 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.

Case 2: a variable breakpoint found a scope bug in minutes

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.

Case 3: traces leaked a secret into the build log

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.

Common errors and fixes

My line breakpoint never fires

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
My -Action prints empty values for variables inside a module function

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.

The debugger stops inside a module function I don't care about

Cause: a command breakpoint (-Command Get-*) matches everywhere. Fix: add -Script to restrict it, or use v (step over) instead of s.

VS Code: “The PowerShell extension's session is not running” / breakpoints are grey

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”).

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

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.

No DEBUG: lines appear with Write-Debug

Cause: the function lacks [CmdletBinding()], so -Debug is not a parameter, or $DebugPreference is SilentlyContinue. Fix: add [CmdletBinding()] and call with -Debug.

Command-line exercises
1. Stop only on the 3rd write to $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).

2. Find every 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 -Recurse
PSDebugContext 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.

Scenario analysis
A health check works when you run it, but in the 02:00 scheduled run it reports every server as down. You cannot reproduce it interactively. What do you do?

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).

Verified teaching videos

▶
Debug PowerShell with and without VS Code — John Savill's Technical Training
English · console debugger and VS Code side by side
▶
Debugging PowerShell Scripts in Visual Studio Code — Adam Driscoll
English · breakpoints, stepping and variables in VS Code
▶
Set Line, Variable, Function, Conditional Breakpoints in PowerShell Scripts — SAPIEN Technologies
English · the breakpoint types of Set-PSBreakpoint
▶
Advanced PowerShell Debugging Techniques — Adam Driscoll
English · jobs, runspaces and remote debugging

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–20s
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.
Shot 2 · 20–55s
Visual: the [DBG] prompt; keys s, v, o, c light up as the cursor moves through the code; the call stack slides in for k.
Narration: step into, over, out, continue — and ask any question at the prompt.
Shot 3 · 55–75s
Visual: a breakpoint with a lightning icon (action) printing lines while the script keeps running.
Narration: an action breakpoint is a log line you add without touching the file.
Shot 4 · 75–90s
Visual: a scheduled task frozen on Wait-Debugger, then a CI check rejecting the commit.
Narration: never ship a breakpoint. Trace and log in unattended runs.
or score ≥ 70% on the Quiz

Module 2 · Static analysis: PSScriptAnalyzer rules, settings, suppression and formatting

06:00 – 13:00 · PSScriptAnalyzer reads your code without running it and flags aliases, plaintext passwords, empty catch blocks, unapproved verbs and dozens of other problems — the PowerShell counterpart of ShellCheck
7 minInvoke-ScriptAnalyzer · Invoke-Formatter★★★★☆
Learning objectives
  • Run Invoke-ScriptAnalyzer on a file, a folder (-Recurse) or a string (-ScriptDefinition) and read RuleName, Severity, Line.
  • Know the three severities (Error, Warning, Information), how many rules each has, and which common rules are Errors.
  • Control analysis with a PSScriptAnalyzerSettings.psd1 — and know that a file with exactly that name next to the analyzed path is used automatically and overrides -Severity.
  • Suppress one finding with [Diagnostics.CodeAnalysis.SuppressMessageAttribute()] and a justification; fix layout with Invoke-Formatter and aliases with -Fix.
Prerequisites: Module 0 (PSScriptAnalyzer 1.25.0). Importance:★★★★☆ (cheapest quality gate you will ever add)

What: rules over the syntax tree

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)SeverityWhy it matters
PSAvoidUsingConvertToSecureStringWithPlainTextErrorThe secret is in the script or the history
PSAvoidUsingPlainTextForPasswordWarningA [string]$Password parameter: use [securestring] or [pscredential]
PSAvoidUsingCmdletAliasesWarninggci, %: unreadable, and differ across platforms (Lesson 1)
PSAvoidUsingWriteHostWarningNot capturable data (exempt in functions with the Show verb)
PSUseApprovedVerbsWarningFetch-Servers → Get-OpsServer; modules warn on import
PSAvoidUsingEmptyCatchBlockWarningSwallowed errors (Lesson 5)
PSPossibleIncorrectComparisonWithNullWarning$rows -eq $null filters an array; write $null -eq $rows
PSUseDeclaredVarsMoreThanAssignmentsWarningAssigned, never used: dead code or a typo
PSUseShouldProcessForStateChangingFunctionsWarningSet-/Remove-/New- functions without SupportsShouldProcess
PSAvoidUsingPositionalParametersInformationOnly for known commands with 3 or more positional arguments (verified)

Why: problems you catch for free

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.

How: settings decide what runs

SettingMeaning
Severity = @('Error','Warning')Report only these severities
IncludeRules / ExcludeRulesAllow-list / deny-list rule names (wildcards)
IncludeDefaultRules = $trueKeep 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

When: in the editor, before commit, in CI

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.

Common misconceptions① “-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.

Diagram: from source to a CI decision

.ps1 / .psm1or -ScriptDefinition Parser → AST+ tokens Settings-Settings file / presetor PSScriptAnalyzerSettings.psd1found next to -Path (automatic) Rules75 built-in+ custom rulesrun on the AST FiltersSeverityInclude/ExcludeSuppressions DiagnosticRecord objectsRuleName · Severity · Line · Message · SuggestedCorrections→ Format-Table for people · count for CI (build fails if > 0)-Fix applies SuggestedCorrections in place Invoke-Formattersame engine, formatting rules onlyreturns the reformatted text(you decide whether to write it back)
Figure 2-1: analysis is a pure function of source + settings; the result is objects, so CI can count them

Analyzer pipeline: what reaches the report?

Each scenario follows one run of Invoke-ScriptAnalyzer on scripts/bad.ps1; the log shows the real result counts from 7.6.10.

Ready.
Real mechanism behind the animation 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 table

CommandPurposeNotes
Invoke-ScriptAnalyzer -Path x.ps1Analyze a file-Recurse for folders
Invoke-ScriptAnalyzer -ScriptDefinition $codeAnalyze a stringGood for quick experiments
-Severity Error, WarningFilterOverridden by a settings file's Severity
-IncludeRule / -ExcludeRulePick rulesWildcards allowed
-Settings ./PSScriptAnalyzerSettings.psd1Use a settings file or preset nameCommit it to the repository
-FixApply suggested corrections in placeRewrites the file: commit first
-IncludeSuppressedShow suppressed records tooIsSuppressed column
Get-ScriptAnalyzerRuleList rules-Name, -Severity
Invoke-Formatter -ScriptDefinition $code -Settings …Reformat textReturns a string

1. A deliberately bad script

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.

2. One rule in detail

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


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


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

3. Settings files — and the automatic pickup

@{
    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.

4. Suppression with a justification

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.

5. Invoke-Formatter and -Fix

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

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

-Fix 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.

Baseline: run Invoke-ScriptAnalyzer ./scripts/bad.ps1 | Sort-Object Line | Format-Table Line, Severity, RuleName and count the records (12 with no settings file).
Auto-fix what can be fixed: Copy-Item ./scripts/bad.ps1 ./scripts/good.ps1; Invoke-ScriptAnalyzer ./scripts/good.ps1 -Fix | Out-Null.
Fix the rest by hand — a reference solution:
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 $_
    }
}
Gate:
$found = Invoke-ScriptAnalyzer ./scripts/good.ps1 -Settings ./settings/PSScriptAnalyzerSettings.psd1
"findings: $(@($found).Count)"; if ($found) { exit 1 }
findings: 0
Format: break the indentation on purpose, then Invoke-Formatter -ScriptDefinition (Get-Content ./scripts/good.ps1 -Raw) -Settings CodeFormattingOTBS and compare.
Cleanup: Remove-Item ./scripts/good.ps1

Case 1: “the analyzer passes locally but fails in CI”

Problem: 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.

Case 2: a plaintext password in a merged script

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.

Case 3: formatting noise drowned a real change

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.

Common errors and fixes

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

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
Different results in VS Code and on the command line

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.

My SuppressMessageAttribute is ignored

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.

Analysis is very slow on a large repository

Cause: compatibility rules (PSUseCompatibleCommands) load large profiles; analyzing node_modules or build output. Fix: analyze only source folders, enable compatibility rules only in CI.

Command-line exercises
1. List every Error-severity rule PSSA 1.25.0 knows.
Get-ScriptAnalyzerRule -Severity Error | Sort-Object RuleName | Select-Object RuleName
2. Fail a pipeline step if any module file has an Error or Warning, printing a table first.
$r = Invoke-ScriptAnalyzer -Path ./OpsKit -Recurse -Settings ./OpsKit/PSScriptAnalyzerSettings.psd1
$r | Format-Table Severity, RuleName, ScriptName, Line -AutoSize
exit [int]([bool]$r)
Scenario analysis
Your team wants to adopt PSSA on a 300-script repository that currently has 2,400 findings. How do you roll it out without blocking everyone?

① 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.

Verified teaching videos

▶
PowerShell+ 2019 - PSScriptAnalyzer (PSSA) VS-code integration & ... by Christoph Bergmeister — Confreaks
English · by a PSScriptAnalyzer maintainer; editor integration and rule configuration
▶
PolarConf 2018: PowerShell Script Analyzer: Good, consistent and pretty code by Jeff Wouters — Finland Azure User Group
English · why consistent style and analysis matter
▶
A Crash Course in Writing Your Own PSScriptAnalyzer Rules by Thomas Rayner — PowerShell.org
English · beyond this lesson: custom rules

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: bad.ps1 with 12 squiggles appearing, one per finding, colored by severity.
Narration: PSScriptAnalyzer reads your code without running it.
Shot 2 · 20–50s
Visual: a settings file slides in next to the script; the -Severity Error filter is crossed out.
Narration: a settings file next to the path is used automatically — pass -Settings explicitly.
Shot 3 · 50–75s
Visual: an attribute with “Justification:” highlighted; IsSuppressed True.
Narration: suppress one finding, with a reason, where it happens.
Shot 4 · 75–90s
Visual: a CI check turning red on a Warning, then green after the fix.
Narration: make the analyzer a gate, not a suggestion.
or score ≥ 70% on the Quiz

Module 3 · Pester basics: Describe / Context / It, Should-* assertions and TestDrive

13:00 – 21:00 · A Pester file is a PowerShell script that Pester runs twice: once to discover the tests, once to run them. Understand the two phases and the rest — blocks, setup, assertions, temp folders, data-driven tests — falls into place
8 minPester 6.2.0★★★★★
Learning objectives
  • Structure a test file with BeforeAll, Describe, Context, It, BeforeEach, AfterEach, AfterAll.
  • Explain Discovery and Run, and reproduce the classic bug: code at the top of a file or directly in Describe runs during discovery, so its variables are gone when It runs.
  • Use the Pester 6 Should-* family (Should-Be, Should-BeString, Should-BeCollection, Should-BeEquivalent, Should-Throw, …) and know where it differs from the classic Should -Be.
  • Isolate file-system tests with TestDrive: / $TestDrive, and generate tests from data with -ForEach and <Name> templates.
Prerequisites: Module 0. Importance:★★★★★ (the foundation of Modules 4, 5 and 8)

What: blocks and their jobs

KeywordJobRuns 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 scopeBody: Discovery
It 'returns 12 servers' { }One test: arrange, act, assertRegistered at Discovery, body at Run
BeforeAll { } / AfterAll { }Once per block (or file, at top level): import the module, build fixturesRun
BeforeEach { } / AfterEach { }Before/after every It in the block and its children: fresh state, mocksRun
BeforeDiscovery { }Compute data that -ForEach needsDiscovery

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).

Why: two phases

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.

How: two assertion syntaxes

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)
StringsShould -BeExactly, -BeLike, -MatchShould-BeString -CaseSensitive, -TrimWhitespace, -NormalizeLineEnding; Should-BeLikeString, Should-MatchString
Booleans / nullShould -BeTrue, -BeNullOrEmptyShould-BeTrue, Should-BeFalse, Should-BeNull, Should-BeTruthy
CollectionsShould -Contain, -HaveCountShould-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)
MocksShould -InvokeShould-Invoke, Should-NotInvoke (Module 4)
Switch off old syntax$config.Should.DisableV5 = $true makes Should -Be throw — useful once a suite is migrated

When: TestDrive and -ForEach

$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).

Common misconceptions① “Code at the top of the test file runs before the tests” — it runs during discovery; its variables are not there at run time (reproduced: 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).

Diagram: one test file, two passes

Get-OpsServer.Tests.ps1 Import-Module … ← top level (D) BeforeAll { Import-Module; $csv } (R) Describe 'Get-OpsServer' { (D) $x = 1 ← body (D only!) Context 'with filters' { (D) BeforeEach { … } (R) It '<Env>' -ForEach @(…) (D: expand) { body } (R) } } D = discovery · R = run Pass 1: Discoveryexecute top level + block bodiesregister It / Before* (not run)expand -ForEach (2 tests)apply filters (tags, names)→ test tree Pass 2: RunBeforeAll (file, block)for each It: BeforeEach → It → AfterEachAfterAllnew scopes; discovery variables goneTestDrive per Describe/Context Pester 6: per file Running tests from 9 files. file 1: discover → run file 2: discover → run … v5 discovered ALL files first, then ran them; side effects of one file's discovery could leak into the next. Each file must import what it needs (Run.BeforeContainer or Pester.BeforeContainer.ps1)
Figure 3-1: the left listing marks which lines run in which pass; a variable set in a D line is not visible to an R line

Core animation: discovery and run, step by step

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.

Ready.
Real mechanism behind the animation 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 table

CommandPurposeNotes
Invoke-Pester -Path ./tests -Output DetailedRun tests with one line per test-Output: None, Normal, Detailed, Diagnostic
Invoke-Pester -FullNameFilter '*retries*'Run matching tests onlyAlso -TagFilter, -ExcludeTagFilter ('None' = untagged)
It 'x' -Tag 'slow', -SkipTag / skip a testSet-ItResult -Skipped -Because '…' inside a test (no -Pending in 6)
Get-Command -Module Pester -Name 'Should-*'List the new assertions41 in 6.2.0
$TestDrive, TestDrive:\Temporary folder per blockDeleted after the block
It '<Env>: <Count>' -ForEach @(@{Env='dev';Count=2})Data-driven testsKeys become variables

The 41 Should-* commands in Pester 6.2.0

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

1. Reproduce the discovery bug

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”.

2. Should-* vs Should -Be (three failures on purpose)

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.

3. Should-BeCollection ignores order

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

Running tests from 1 files.

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

4. Pester 6 strictness: empty -ForEach, filtered mocks, DisableV5

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

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

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

Running tests from 1 files.

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

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.

5. The first real OpsKit tests: Get-OpsServer with TestDrive and -ForEach

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.

Get-OpsConfig — a fixture config, deep comparison with 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*"
    }
}
Invoke-OpsBackup — a fresh source and destination per test (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:*'
    }
}
Run them:
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.

Break it on purpose: change 'backup-{0}.zip' to 'bak-{0}.zip' in Invoke-OpsBackup.ps1, re-run, read which tests fail and why, then revert.
Cleanup: nothing to clean — TestDrive folders are deleted by Pester.

Case 1: green tests, broken module

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.

Case 2: the build server ran Pester 3.4

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.

Case 3: tests that pass alone and fail together

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.

Common errors and fixes

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

Cause: Pester 3/4 is loaded. Fix: Get-Module Pester; Remove-Module Pester; Import-Module Pester -MinimumVersion 6.0.0.

Expected [int] 12, but got [int] 0 / a variable is $null inside It

Cause: the variable was assigned during discovery. Fix: move it into BeforeAll or BeforeEach.

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

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.

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

Cause: Should.DisableV5 = $true in the configuration (or $PesterPreference). Fix: migrate the assertion, or set it back to $false.

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

Cause: the Pending status was removed in Pester 6. Fix: Set-ItResult -Skipped -Because '…' or -Inconclusive.

Command-line exercises
1. Write a data-driven test that checks the server count per environment in ~/pslab/data/servers.csv (dev 3, staging 3, prod 6).
BeforeAll { Import-Module ~/pslab/OpsKit/OpsKit.psd1 -Force }
Describe 'dataset' {
    It '<Env> has <Count> servers' -ForEach @(
        @{ Env = 'dev'; Count = 3 }, @{ Env = 'staging'; Count = 3 }, @{ Env = 'prod'; Count = 6 }
    ) {
        @(Get-OpsServer -Path ~/pslab/data/servers.csv -Environment $Env).Count | Should-Be $Count
    }
}
2. Run only the tests whose name contains “WhatIf”, with detailed output.
Invoke-Pester -Path ./OpsKit/tests -FullNameFilter '*WhatIf*' -Output Detailed
Scenario analysis
A colleague's test file loads 5,000 rows from a CSV at the top of the file to build -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.

Verified teaching videos

▶
PowerShell 7 Tutorials for Intermediates #5 : Pester (Testing) — JackedProgrammer
English · Describe / It / Should with Pester 5 syntax
▶
Unit Testing with Pester Framework | PowerShell Testing Tutorial for Beginners — CodeLucky
English · first unit tests

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.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: a test file; a yellow scanner (Discovery) passes over it, lighting Describe/Context bodies and registering It boxes without opening them.
Narration: Pester reads your file twice.
Shot 2 · 25–55s
Visual: a green scanner (Run) opens BeforeAll, then each It; a variable from the yellow pass fades out.
Narration: setup belongs in BeforeAll — anything else is gone by the time tests run.
Shot 3 · 55–75s
Visual: Should-Be, Should-BeString, Should-BeEquivalent cards with their failure messages.
Narration: Pester 6 assertions are typed and explain failures precisely.
Shot 4 · 75–90s
Visual: a TestDrive folder appearing and vanishing around a Describe block.
Narration: every file a test writes goes to TestDrive.
or score ≥ 70% on the Quiz

Module 4 · Mocking and test design: Mock, Should -Invoke, InModuleScope

21:00 – 28:00 · Unit tests must not call real web servers, clocks or clouds. Mock replaces a command for the duration of a test, records every call, and lets you assert how your code used it — as long as you put the mock in the right scope
7 minMock · Should-Invoke · InModuleScope★★★★★
Learning objectives
  • Mock a command with a replacement body, conditionally with -ParameterFilter, and know that in Pester 6 a call that matches no filter and has no default mock throws.
  • Use -ModuleName OpsKit so a mock reaches calls made inside the module, and InModuleScope to call private functions.
  • Assert calls with Should-Invoke / Should-NotInvoke (or classic Should -Invoke), with -Times, -Exactly and filters, and read the invocation history Pester prints on failure.
  • Test -WhatIf, error paths (Should-Throw), retries (mocked Invoke-RestMethod + Start-Sleep), native commands (git) and commands that are not installed (Get-AzResource).
Prerequisites: Module 3, Lesson 4 (module scope), Lesson 7 (Invoke-OpsApi). Importance:★★★★★

What: a mock is a function that wins command lookup

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.

Why: fast, deterministic, offline

DependencyProblem in a unit testMock it as
Invoke-WebRequest, Invoke-RestMethodNetwork, slow, flaky, real side effectsReturn [pscustomobject]@{ StatusCode = 503 } or throw an HttpResponseException
Get-DateChanges every run{ '20261124-101500' }
Start-SleepRetry back-off makes tests slow{ } and count the calls
Remove-Item, Restart-ServiceDestructive{ } + Should-Invoke with a filter
git, az, kubectlNative tool not installed in CI, or needs credentialsMock git { 'main' } (works for applications too)
Get-AzResourceModule not installed on the runnerDefine a stub function first, then mock it (Mock needs the command to exist)

How: scope decides whether the mock is seen

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 directlyInModuleScope 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.

When: filters, defaults and verification

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.

Common misconceptions① “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.

Diagram: which caller sees which mock

Test scope (Pester container) Mock Invoke-WebRequest { 200 }visible only to calls made from this scope Test-OpsEndpoint -Uri …exported function: its body runs in OpsKit's scope InModuleScope OpsKit { Resolve-OpsPath '~' }runs the block inside the module: private functions visible Module scope: OpsKit Mock Invoke-WebRequest -ModuleName OpsKit { 200 }injected here: calls inside OpsKit get it Test-OpsEndpoint bodyInvoke-WebRequest -Uri $Uri -TimeoutSec … Private: Resolve-OpsPath, Write-OpsLognot exported → not callable from tests directly
Figure 4-1: the call to Invoke-WebRequest happens in OpsKit's scope, so only a mock injected with -ModuleName OpsKit replaces it

Mock resolver: what does this call hit?

Each scenario follows one call from code under test to whatever answers it.

Ready.
Real mechanism behind the animation 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 table

CommandPurposeNotes
Mock Cmd { … }Default replacementDefine in BeforeAll/BeforeEach/It
Mock Cmd -ParameterFilter { $Name -eq 'x' } { … }Conditional replacementVariables are the command's parameters (aliases work)
Mock Cmd -ModuleName OpsKit { … }Mock calls made inside a moduleUse the same -ModuleName on Should-Invoke
Should-Invoke Cmd -Times 2 -Exactly -ModuleName OpsKitAssert the call countClassic: Should -Invoke Cmd -Times 2 -Exactly
Should-NotInvoke Cmd -ModuleName OpsKitAssert no callGreat for -WhatIf tests
InModuleScope OpsKit -Parameters @{ P = 1 } { … }Run code inside the modulePrivate functions and $script: variables
New-MockObject -Type System.Diagnostics.ProcessA fake .NET object of a typeWhen a parameter is strongly typed
{ … } | Should-Throw -ExceptionMessage '*404*' -ExceptionType ([…])Error pathWrap the call in a script block

1. Mock scope, a native command, and invocation history

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.

2. Test-OpsEndpoint: default + filtered mocks

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.

3. Invoke-OpsApi: retries, bodies and -WhatIf without a server

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.

4. Private functions with InModuleScope, and a command that is not installed

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.

Read the function:
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
        }
    }
}
Write the tests — mock 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
        }
    }
}
Run:
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
Experiment: remove -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.
Cleanup: none (TestDrive, and $env:OPSKIT_LOG is removed in finally).

Case 1: the unit tests restarted a real service

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.

Case 2: a 20-minute test suite

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.

Case 3: upgrading to Pester 6 broke 40 tests

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.

Common errors and fixes

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

Cause: the call happened inside a module and the mock or the assertion lacks -ModuleName. Fix: add -ModuleName OpsKit to both.

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

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.

CommandNotFoundException: Could not find Command Get-AzResource

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.

Inside InModuleScope my test variables are $null

Cause: the script block runs in the module's scope. Fix: pass values with -Parameters @{ Path = $Path } (they become variables inside).

Mocks do not apply inside ForEach-Object -Parallel or jobs

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.

Command-line exercises
1. Assert that 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 OpsKit
2. Mock Get-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 calls
Scenario analysis
A teammate wants to test Invoke-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.

Verified teaching videos

▶
Testing, Testing, 1...2...3: Using Pester for Infrastructure Validation by Brandon Olin — PowerShell.org
English · test design, mocking and what to test (conference talk)
▶
PowerShell 7 Tutorials for Intermediates #5 : Pester (Testing) — JackedProgrammer
English · includes Mock basics (Pester 5 syntax)

Both predate Pester 6 (no Should-Invoke, and fall-through still existed). No verified video covering Pester 6 mocking changes was found.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: Test-OpsEndpoint reaching out to the internet; a mock “plug” snaps in front of Invoke-WebRequest — but outside the module wall, so the call passes by.
Narration: a mock must live where the call happens.
Shot 2 · 25–55s
Visual: the plug moves inside the OpsKit wall (-ModuleName); the call now hits it; a counter ticks.
Narration: -ModuleName injects the mock into the module; Should-Invoke counts the calls.
Shot 3 · 55–75s
Visual: 503, 503, 200 bubbles; Start-Sleep icons crossed out.
Narration: test retries without waiting.
Shot 4 · 75–90s
Visual: a call matching no filter hitting a red wall “no fall-through”.
Narration: in Pester 6 every call needs a mock that answers it.
or score ≥ 70% on the Quiz

Module 5 · Coverage and CI output: code coverage and test result files

28:00 – 35:00 · A CI system understands three things: an exit code, a test-result XML file and a coverage XML file. New-PesterConfiguration produces all three — if you set the right options
7 minNew-PesterConfiguration · JaCoCo · NUnit★★★★☆
Learning objectives
  • Build a run with New-PesterConfiguration: Run.Path, Run.PassThru, Output.Verbosity, CodeCoverage.*, TestResult.*.
  • Produce JaCoCo (or Cobertura) coverage and NUnitXml / NUnit3 / JUnitXml results, and read CoveragePercent and the missed commands.
  • Control the process result: 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.
Prerequisites: Modules 3–4. Importance:★★★★☆

What: the configuration object

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.OptionUseDefault
Run.Path, Run.ExcludePathTest files/folders.
Run.PassThruReturn the result object$false
Run.ExitExit the process with a non-zero code when tests fail$false
Run.ThrowThrow when tests fail (preferred over Exit when both are set)$false
Output.VerbosityNone, Normal, Detailed, DiagnosticNormal
Output.CIFormatAuto, AzureDevops, GithubActions (error annotations)Auto
CodeCoverage.Enabled / Path / OutputFormat / OutputPathCoverage of these files, as JaCoCo or Coberturaoff; JaCoCo; coverage.xml
CodeCoverage.CoveragePercentTargetTarget shown in the summary75
CodeCoverage.UseBreakpointsOld breakpoint-based coverage$false (profiler-based since 6.0)
TestResult.Enabled / OutputFormat / OutputPathNUnitXml, NUnit2.5, NUnit3, JUnitXmloff; NUnitXml; testResults.xml
Should.DisableV5Forbid Should -Be$false

Why: three signals for CI

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”.

How: what coverage measures

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.

When: exit codes

ConfigurationTests fail → what happensVerified
Nothing setSummary printed, process exit code 0✓ Result=Failed Failed=2, exit 0
Run.Exit = $trueexit with the number of failed tests✓ exit 2 for 2 failures; next line not reached
Run.Throw = $trueTerminating error “Pester run failed, because 2 tests failed”✓
Invoke-Pester -CITestResult.Enabled + Run.Exit (coverage not included)✓ wrote testResults.xml, exit 2
Coverage below CoveragePercentTargetOnly reported: “Covered 29.34% / 80%”; exit 0✓ — enforce it yourself (Module 8)
Common misconceptions① “If tests fail, 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.

Diagram: one run, three outputs

New-PesterConfigurationRun.Path = ./testsCodeCoverage.Path = Public, PrivateTestResult.OutputFormatRun.Exit / Throw / PassThru Invoke-Pesterper file: discover → runprofiler records executedcommands in covered filesresult tree [Pester.Run] out/testResults.xmlNUnitXml · NUnit3 · JUnitXml → test tab in CI out/coverage.xmlJaCoCo · Cobertura → coverage report / gutters exit codeRun.Exit: failed count · else 0 (!)
Figure 5-1: the exit code is the only output CI acts on automatically; set it deliberately

From test run to CI status

Ready.
Real mechanism behind the animation After the last container, Pester builds the run result, writes the configured report files, and then applies the failure policy: with 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 table

CommandPurpose
$c = New-PesterConfigurationStart from defaults
[PesterConfiguration]::Default.Run.Exit.DescriptionRead the built-in documentation of an option
$r = Invoke-Pester -Configuration $cRun (with Run.PassThru)
$r.Result, $r.FailedCount, $r.FailedOutcome, count, failed test objects
$r.CodeCoverage.CoveragePercent, .CommandsMissedCoverage numbers and missed statements (File, Line, Command)
Invoke-Pester -CIShortcut: TestResult + Exit

1. Full OpsKit run with coverage and JUnit results

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).

2. What the files look like

<?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.

3. Coverage below target does not fail the run

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

4. Exit codes: Run.Exit, Run.Throw, default

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.

Write it:
#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.0.0' }
param([int]$Threshold = 80)
$c = New-PesterConfiguration
$c.Run.Path = "$PSScriptRoot"
$c.Run.PassThru = $true
$c.CodeCoverage.Enabled = $true
$c.CodeCoverage.Path = "$PSScriptRoot/../Public", "$PSScriptRoot/../Private"
$c.CodeCoverage.OutputPath = "$PSScriptRoot/../out/coverage.xml"
$c.TestResult.Enabled = $true
$c.TestResult.OutputPath = "$PSScriptRoot/../out/testResults.xml"
$r = Invoke-Pester -Configuration $c
if ($r.FailedCount -gt 0) { exit 1 }
if ($r.CodeCoverage.CoveragePercent -lt $Threshold) { Write-Warning "coverage $($r.CodeCoverage.CoveragePercent)% below $Threshold%"; exit 3 }
exit 0
Run it as CI would: pwsh -NoProfile -NonInteractive -File ./OpsKit/tests/run.ps1; "exit=$LASTEXITCODE" → exit=0.
Lower coverage on purpose: temporarily move 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.

See the missed lines: $r.CodeCoverage.CommandsMissed | Format-Table File, Line, Command (add Run.PassThru and keep $r).
Cleanup: move the test file back; Remove-Item ./OpsKit/out -Recurse.

Case 1: green pipeline, red tests

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.

Case 2: coverage “fell” from 85% to 40% overnight

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.

Case 3: a results file revealed internal host names

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.

Common errors and fixes

Coverage is 0% / “0 analyzed Commands”

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.

The CI system shows no tests

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().

The configuration rejects a value (Pester 6.2)

Cause: 6.2 validates values instead of silently ignoring them (release notes). Fix: read [PesterConfiguration]::Default.Section.Option.Description for the allowed values.

Coverage numbers differ from Pester 5

Cause: Pester 6 uses the profiler tracer by default. Fix: accept the new baseline, or set CodeCoverage.UseBreakpoints = $true temporarily to compare.

Command-line exercises
1. Produce Cobertura coverage and NUnit3 results instead of the defaults.
$c = New-PesterConfiguration
$c.Run.Path = './OpsKit/tests'
$c.CodeCoverage.Enabled = $true; $c.CodeCoverage.Path = './OpsKit/Public', './OpsKit/Private'
$c.CodeCoverage.OutputFormat = 'Cobertura'
$c.TestResult.Enabled = $true; $c.TestResult.OutputFormat = 'NUnit3'
Invoke-Pester -Configuration $c
2. Print the three least-covered files from a PassThru result.
$r.CodeCoverage.CommandsMissed | Group-Object File -NoElement | Sort-Object Count -Descending | Select-Object -First 3
Scenario analysis
Management asks for “100% coverage” on OpsKit. You already have 100% command coverage. Is the job done?

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.

Verified teaching videos

▶
GitHub Actions for Fun and Profit by Adam Driscoll — PowerShell.org
English · running PowerShell tests in CI

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.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–30s
Visual: Invoke-Pester with three output pipes: XML results, XML coverage, exit code.
Narration: CI needs three things.
Shot 2 · 30–60s
Visual: two failing tests, pipeline stays green; then Run.Exit flips it red.
Narration: without Run.Exit, failures still exit zero.
Shot 3 · 60–90s
Visual: “Covered 32% / 80%” with exit 0; a build script check turns it red.
Narration: enforce coverage yourself.
or score ≥ 70% on the Quiz

Module 6 · Performance: Measure-Command, collection building and pipeline cost

35:00 – 42:00 · Most slow PowerShell comes from a handful of patterns: growing arrays with +=, building strings with +=, piping huge collections through script blocks, and filtering on the wrong side of the pipeline. Measure first, then fix the pattern
7 minMeasure-Command★★★☆☆
Learning objectives
  • Time code with Measure-Command correctly (warm-up, best of several runs, output discarded, scope effects).
  • Compare array +=, List[T].Add() and pipeline capture ($a = foreach (…) { … }), and string +=, StringBuilder and -join.
  • Compare ForEach-Object vs foreach vs .ForEach(), and Where-Object vs .Where().
  • Apply filter left: -Filter at the provider beats Where-Object, and -Include can be slower than both.
Prerequisites: Lesson 2 (collections, loops). Importance:★★★☆☆ (matters for large data; irrelevant for 12 servers)

What: where time goes

PatternWhy it costsBetter
$a += $x in a loopArrays are fixed-size: each += allocates a new array and copies everything (O(n²))$a = foreach (…) { $x } or List[T]
$s += "…" in a loopStrings are immutable: each += copies the whole string-join over a captured collection, or StringBuilder
… | ForEach-Object { } on 100k itemsPipeline overhead + a script block invocation per itemforeach statement on data already in memory
Get-ChildItem | Where-ObjectEvery file becomes an object first, then most are thrown away-Filter (provider-side)
Get-ChildItem -IncludeImplemented as a post-filter with extra path handling-Filter when one pattern is enough

Why: measured on the lab machine

Real timings from 7.6.10 (best of 3, milliseconds; your numbers will differ, the ratios are what matter):

20,000 itemsms100,000 itemsms
array +=1446ForEach-Object { }181.5
List[int].Add()297.7foreach ($x in $data) { }38.3
$a = foreach (…) { $i }22.1$data.ForEach({ })107.9
string +=1046Where-Object { }265.0
StringBuilder113.9$data.Where({ })80.3
-join over captured lines41.2foreach + if51.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.

How: measure properly

  • Warm up once (first run pays for compilation and type loading).
  • Take the best of N runs (or the median); one number is noise.
  • 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).
  • Measure with realistic sizes: at 12 items nothing matters; at 100k it does.

When: optimize only hot paths

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.

Common misconceptions① “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.

Diagram: why += is quadratic

$a += $i (copy every time) 1 1 2 1 2 3 1 2 3 4 n allocations, 1+2+…+n copies ≈ n²/2 20,000 items: 1446 ms $a = foreach (…) { $i } (collect once) pipeline output buffer grows geometrically one object[] at the end amortized O(n) 20,000 items: 22.1 ms
Figure 6-1: the same result, two allocation strategies; the difference grows with n

Diagram: filter left

2,000 files 2,000 FileInfo objects→ Where-Object → 200 (64 ms) -Filter *.log at the file system→ 200 objects only (4.4 ms) -Include *.log (needs path\*)post-filter + path work: 134 ms
Figure 6-2: -Filter is passed to the provider (the OS API); -Include and Where-Object work on objects already created

Cost race: same result, different price

Ready.
Real mechanism behind the animation The engine compiles script blocks to expression trees and caches them; a 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 table

Command / patternUse
Measure-Command { … }Returns a TimeSpan; output discarded
(Measure-Command { … }).TotalMillisecondsOne 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

1. Building collections and strings

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

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

2. Loops and filters over 100,000 numbers

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

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

3. Filter left on the file system, and Measure-Command's scope

# 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.

Make a big file:
$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
Slow version:
Measure-Command {
    $errors = @()
    Get-Content ~/pslab/tmp/big.log | ForEach-Object {
        if ($_ -match '" 5\d\d ') { $errors += $_ }
    }
}
Faster versions — compare all three and check each returns 2,000 lines (20 × 100):
Measure-Command { $errors = foreach ($l in [IO.File]::ReadLines("$HOME/pslab/tmp/big.log")) { if ($l -match '" 5\d\d ') { $l } } }
Measure-Command { $errors = (Get-Content ~/pslab/tmp/big.log).Where({ $_ -match '" 5\d\d ' }) }
Measure-Command { $errors = Select-String -Path ~/pslab/tmp/big.log -Pattern '" 5\d\d ' }
Record your numbers in a table like the one in Principles; note which version is the most readable for its speed.
Cleanup: Remove-Item ~/pslab/tmp/big.log

Case 1: an inventory report took 40 minutes

Problem: 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.

Case 2: a cleanup job hammered the file server

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.

Case 3: a timing test failed randomly in CI

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.

Common errors and fixes

Measure-Command returns tiny times but the script feels slow

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.

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

Cause: calling .Add() on a plain array. Fix: create a List[T], or use pipeline capture.

My List[int] became object[] after a function returned it

Cause: returning a collection unrolls it into the pipeline. Fix: return ,$list or Write-Output -NoEnumerate $list when the type matters.

.Where() returns a Collection`1, not an array

Cause: .Where() and .ForEach() return Collection[psobject]. It behaves like an array for indexing and .Count; convert with @(…) if an API needs object[].

Command-line exercises
1. Write a 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
}
2. Rewrite $out = @(); foreach ($s in Get-OpsServer) { if ($s.Monitored) { $out += $s.Name } } without +=.
$out = foreach ($s in Get-OpsServer) { if ($s.Monitored) { $s.Name } }
Scenario analysis
A colleague replaces every 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.

Verified teaching videos

▶
Make Your PowerShell Scripts Faster! — Jeff Brown Tech
English · array addition, suppressing output, pipelines
▶
#PowerShell Generic List in seconds - performance comparison between array and list at the end — Kamil Pro
English · short; array vs List[T]

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–30s
Visual: an array box being copied into a slightly bigger box, again and again; a timer racing.
Narration: += copies everything, every time.
Shot 2 · 30–60s
Visual: bar chart 1446 / 298 / 22 ms.
Narration: let the foreach statement collect the results.
Shot 3 · 60–90s
Visual: a file server; -Filter arrow stops at the server, Where-Object arrow carries 2,000 boxes over the wire.
Narration: filter left, at the source.
or score ≥ 70% on the Quiz

Module 7 · Security and release: signing, SemVer, changelog and a GitHub Actions workflow

42:00 – 50:00 · A release is a promise: this code, at this version, built and tested this way, by us. Authenticode signatures, constrained language mode, semantic versions, a changelog and a CI workflow are how PowerShell teams keep that promise
8 minAuthenticode · SemVer · GitHub Actions★★★★☆
Learning objectives
  • Check a signature with Get-AuthenticodeSignature, know how Set-AuthenticodeSignature signs a script with a code-signing certificate, and what AllSigned and RemoteSigned require.
  • Explain constrained language mode (CLM): what it blocks, when it is enforced (App Control/WDAC, AppLocker), and why modules should not depend on full language features unnecessarily.
  • Version a module with SemVer: ModuleVersion ([version], no label) plus PrivateData.PSData.Prerelease; compare versions with [semver]; keep a CHANGELOG.md.
  • Write .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.
Prerequisites: Lesson 1 (execution policy), Lesson 4 (manifests, PSResourceGet), Lesson 7 (secrets). Importance:★★★★☆

What: three layers of trust

LayerQuestion it answersPowerShell mechanism
Integrity + originWas this file changed since X signed it?Authenticode signature block at the end of .ps1/.psm1/.psd1; Get-AuthenticodeSignature → Valid, NotSigned, HashMismatch, NotTrusted
PolicyMay 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)
EnforcementWhat may untrusted code do?App Control for Business (WDAC) / AppLocker put untrusted scripts into ConstrainedLanguage; trusted (allowed-signed) code runs in FullLanguage

Why: constrained language mode in one table

Allowed in CLMBlocked 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, variablesAdd-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.

How: SemVer for PowerShell modules

ChangeBumpOpsKit example
Breaking: removed/renamed function or parameter, changed output typeMAJOR0.5.0 → 1.0.0 (1.0 = “public API is now stable”)
New function or optional parameterMINOR1.0.0 → 1.1.0 adds Get-OpsReport
Bug fix, no API changePATCH1.1.0 → 1.1.1
Pre-releaselabelModuleVersion = '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.

When: the release workflow

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.

Common misconceptions① “Signed means safe” — it means unchanged since a known publisher signed it; malware can be signed too. ② “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.

Diagram: the OpsKit release pipeline

git pushPR · main · tag v1.0.0 job: test (matrix) windows ubuntu macos checkout · shell: pwsh Install-PSResource Pester 6.2.0, PSSA 1.25.0 ./build.ps1 -Task Analyze ./build.ps1 -Task Test (exit 1 on failure) upload-artifact (if: always()) testResults.xml · coverage.xml needs job: publish (only refs/tags/v*) environment: psgallery (approval) tag == v + ModuleVersion [+ -Prerelease] ? ./build.ps1 -Task Package Publish-PSResource -ApiKey $env:PSGALLERY_API_KEY secrets.PSGALLERY_API_KEY (environment secret) PowerShell GalleryOpsKit 1.0.0
Figure 7-1: tests gate everything; only a tag on a commit that passed on all three OSes reaches the publish job

Release pipeline: what runs for this event?

Ready.
Real mechanism behind the animation GitHub Actions evaluates 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 table

CommandPurposeNotes
Get-AuthenticodeSignature ./x.ps1Signature status and signerRead-only; works on any file type that supports Authenticode
Set-AuthenticodeSignature -FilePath x.ps1 -Certificate $cert -TimestampServer http://timestamp.digicert.comSignNeeds a code-signing certificate; timestamp so the signature outlives the certificate
Get-ExecutionPolicy -ListEffective policy per scopeLesson 1
$ExecutionContext.SessionState.LanguageModeFullLanguage / ConstrainedLanguageSetting 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 rc1Edit a manifestPSResourceGet; rewrites the whole file
Test-ModuleManifest ./OpsKit.psd1Validate and read a manifestThrows on broken manifests
Publish-PSResource -Path dir -Repository PSGallery -ApiKey $keyPublish-DestinationPath also saves the .nupkg

1. Signatures, policy and constrained language (read-only)

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.

2. Signing (Expected — not run, because it creates a certificate in the user's store)

# 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.

3. SemVer and the manifest

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

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

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

4. CHANGELOG.md

# Changelog

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

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

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

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

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

5. .github/workflows/opskit.yml

name: OpsKit CI

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

permissions:
  contents: read

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

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

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

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

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

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

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

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

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

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

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).

Check signatures and language mode on your machine: Get-ChildItem ./OpsKit -Recurse -Include *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Group-Object Status -NoElement and $ExecutionContext.SessionState.LanguageMode.
Try CLM in a throw-away process:
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.

Write CHANGELOG.md with sections Added / Changed / Fixed for 1.0.0 (see Commands).
Write the workflow to ./OpsKit/.github/workflows/opskit.yml, then validate it: Install-PSResource powershell-yaml -Scope CurrentUser (or Save-PSResource) and run the validation script from Commands.
Compare versions: predict, then check [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'.
Cleanup: nothing to clean; the workflow file stays for Module 8.

Case 1: a hotfix broke every server with AllSigned

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.

Case 2: 1.0.0-rc10 installed instead of 1.0.0-rc9… or not

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.

Case 3: the API key leaked in a log

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.

Common errors and fixes

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

Cause: AllSigned (or RemoteSigned with a Zone.Identifier mark). Fix: sign it in the build, or Unblock-File after review for downloaded files.

Get-AuthenticodeSignature: HashMismatch

Cause: the file changed after signing (including line-ending conversion by Git: set *.ps1 -text or eol=crlf in .gitattributes for signed files).

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

Cause: a label in ModuleVersion. Fix: ModuleVersion = '1.0.0' and Prerelease = 'rc1'.

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

Cause: verified with PSResourceGet 1.2.1: the manifest contains Prerelease = ''. Fix: delete the empty Prerelease line (Module 8).

Workflow: “Invalid workflow file … mapping values are not allowed here”

Cause: YAML indentation or an unquoted value containing : . Fix: validate locally (Commands step 5), quote expressions, and keep run: | blocks indented consistently.

Command-line exercises
1. List all files in OpsKit that are not validly signed.
Get-ChildItem ./OpsKit -Recurse -Include *.ps1, *.psm1, *.psd1 | Get-AuthenticodeSignature |
    Where-Object Status -ne 'Valid' | Select-Object Status, Path
2. Compute the full version string (with prerelease) from a manifest.
$m = Test-ModuleManifest ./OpsKit/OpsKit.psd1
$v = "$($m.Version)"; if ($m.PrivateData.PSData.Prerelease) { $v += "-$($m.PrivateData.PSData.Prerelease)" }
$v
Scenario analysis
Security asks you to make OpsKit “AllSigned compliant” for a fleet of servers that also enforce App Control. What is your plan?

① 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.

Verified teaching videos

▶
Streamline Module Publishing to PowerShell Gallery Using GitHub Actions — Jeff Brown Tech
English · test and publish from a workflow
▶
GitHub Actions for Fun and Profit by Adam Driscoll — PowerShell.org
English · PowerShell in GitHub Actions

No verified video on Authenticode signing or constrained language mode was found; use the documentation below.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: a script with a wax seal (signature); one character changes, the seal cracks (HashMismatch).
Narration: a signature proves who and unchanged — sign last.
Shot 2 · 25–50s
Visual: a locked-down machine; an unsigned module's [pscustomobject] line flashes red.
Narration: on App Control machines, untrusted code runs in constrained language mode.
Shot 3 · 50–90s
Visual: the three-OS matrix lighting green, then the tag v1.0.0 opening the publish gate.
Narration: test everywhere, publish only from a tag that matches the manifest.
or score ≥ 70% on the Quiz

Module 8 · OpsKit v1.0: tests, analysis, CI and release

50:00 – 60:00 · Put everything together: a full test suite with 100% command coverage, a clean analyzer run, version 1.0.0, a build.ps1 with Analyze / Test / Package tasks that CI and humans run the same way, and a .nupkg in a local folder repository
10 minbuild.ps1 · Compress-PSResource★★★★★
Learning objectives
  • Organize tests per public function plus module-level tests (manifest, exports, help), and reach the 80% coverage threshold — OpsKit reaches 100%.
  • Make the analyzer clean with a project settings file and Invoke-Formatter.
  • Bump to 1.0.0 with Update-PSModuleManifest and handle its Prerelease = '' failure.
  • Write 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.
Prerequisites: Modules 2–7; Lesson 4 (repositories). Importance:★★★★★ (this is the milestone)

What: the v1.0 definition of done

GateThresholdOpsKit 1.0.0 result (verified)
Unit testsAll pass on Windows, Ubuntu, macOS51 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
PSScriptAnalyzer0 Errors and 0 Warnings with the project settings0 findings (after fixing 3 brace-placement warnings)
ManifestModuleVersion = '1.0.0', valid, exports = Public/*.ps1Test-ModuleManifest: 1.0.0, 7 functions
PackageA .nupkg with only module filesOpsKit.1.0.0.nupkg, 10,808 bytes, 12 files + nuspec
DocumentationHelp with an example for each public function; CHANGELOGEnforced by OpsKit.Module.Tests.ps1

Why: one build script for people and CI

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).

How: the test layout

FileTestsTechniques
Get-OpsServer.Tests.ps19TestDrive fixture, -ForEach, Should-All, classic Should
Get-OpsConfig.Tests.ps16Should-BeEquivalent, Should-Throw -ExceptionType/-ExceptionMessage
Invoke-OpsBackup.Tests.ps17BeforeEach isolation, Mock Get-Date, -WhatIf, Should-Invoke Remove-Item
Test-OpsEndpoint.Tests.ps15Default + filtered mocks of Invoke-WebRequest, pipeline input
Invoke-OpsApi.Tests.ps16Retry sequences, HttpResponseException, Mock Start-Sleep, Should-NotInvoke
Invoke-OpsHealthCheck.Tests.ps13Mocking a public function used internally, log file in TestDrive
Get-OpsCloudInventory.Tests.ps12Stub for a command that is not installed, mocking Get-Command
Private.Tests.ps14InModuleScope -Parameters
OpsKit.Module.Tests.ps19Manifest, exports = Public folder, help per function (-ForEach at discovery)

When: release steps in order

① 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).

Common misconceptions① “100% coverage, so the build can't miss bugs” — breaking 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.

Diagram: build.ps1

./build.ps1-Task All-CoverageThreshold 80 AnalyzeInvoke-ScriptAnalyzer-Settings project filepsm1 + Public + Privateany finding → throw TestPester 6 configurationcoverage.xml · testResults.xmlFailedCount > 0 → throwcoverage < threshold → throw PackageTest-ModuleManifeststage psd1 psm1 Public Private CHANGELOGCompress-PSResource → out/repoOpsKit.1.0.0.nupkg catch → “Build failed: …” → exit 1 · success → “Build succeeded.” → exit 0
Figure 8-1: each task throws on failure; one catch turns any failure into exit code 1 for CI

build.ps1 gatekeeper

The logs are the real outputs of the runs recorded for this lesson.

Ready.
Real mechanism behind the animation Each task function either completes or throws; $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 table

CommandPurpose
./build.ps1 / -Task Analyze, TestRun all or selected tasks
Update-PSModuleManifest -Path ./OpsKit.psd1 -ModuleVersion 1.0.0Bump the version
Compress-PSResource -Path ./out/stage/OpsKit -DestinationPath ./out/repoCreate the .nupkg without publishing
Register-PSResourceRepository -Name OpsKitLocal -Uri ~/pslab/OpsKit/out/repo -TrustedFolder repository (Lesson 4)
Install-PSResource OpsKit -Version 1.0.0 -Repository OpsKitLocal -Scope CurrentUserSmoke-test the package

1. Before: OpsKit v0.5 coverage

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

2. All tests

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

Running tests from 9 files.

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

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

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

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

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

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

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

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

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

3. The project analyzer settings, and the first Analyze run

@{
    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.

4. Version 1.0.0 — and an Update-PSModuleManifest bug

@{
    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.

5. build.ps1

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

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

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

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

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

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

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

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

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

6. The build catches a real bug

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.

7. Publish to a folder repository and install (Expected — not run: it changes the user's repository list)

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.

8. Reference: the OpsKit 1.0.0 source

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

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

        [string]$Role,

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

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

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

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

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

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

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

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

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

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

Test-OpsEndpoint, Invoke-OpsApi and Invoke-OpsHealthCheck and their tests are listed in Module 4; Get-OpsServer, Get-OpsConfig and Invoke-OpsBackup tests in Module 3.

Interactive troubleshooting tree: “the build is red”

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.

Tests: copy the 9 test files from Modules 3, 4 and 8 into ~/pslab/OpsKit/tests; Invoke-Pester ./tests → 51 passed.
Analyzer: add PSScriptAnalyzerSettings.psd1; run ./build.ps1 -Task Analyze; fix findings with Invoke-Formatter -Settings or by hand until “Analyze: 0 findings.”
Version: add the 1.0.0 entry to CHANGELOG.md; remove an empty Prerelease = '' if present; Update-PSModuleManifest -Path ./OpsKit.psd1 -ModuleVersion 1.0.0; Test-ModuleManifest ./OpsKit.psd1.
Build: pwsh -NoProfile -NonInteractive -File ./build.ps1; "exit=$LASTEXITCODE" → Build succeeded., exit=0, and out/repo/OpsKit.1.0.0.nupkg.
Smoke test (optional, changes your repository list): register out/repo as a folder repository and install, as in Commands step 7; unregister afterwards with Unregister-PSResourceRepository OpsKitLocal and Uninstall-PSResource OpsKit.
Cleanup: Remove-Item ./out -Recurse (build output only; it is recreated on every build).

Case 1: the package contained the test fixtures and an API key

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.

Case 2: “works on my machine” because of a stale module

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.

Case 3: the version bump that rewrote the manifest

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.

Common errors and fixes

Build failed: Analyze: N finding(s).

Read the table above the message; fix or justify each finding. Invoke-Formatter -Settings ./PSScriptAnalyzerSettings.psd1 fixes layout rules.

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

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.

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

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.

Command-line exercises
1. Add a 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
2. List the files inside the produced .nupkg.
$zip = [System.IO.Compression.ZipFile]::OpenRead((Resolve-Path ./out/repo/OpsKit.1.0.0.nupkg))
$zip.Entries.FullName | Sort-Object; $zip.Dispose()
Scenario analysis
The day after release, a user reports that 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.

Verified teaching videos

▶
CODE2327LV: Build and Publish a PowerShell Module to the PowerShell Gallery — VMware {code}
English · building and publishing a module end to end
▶
Streamline Module Publishing to PowerShell Gallery Using GitHub Actions — Jeff Brown Tech
English · automating the release

These videos use PowerShellGet's Publish-Module; this lesson uses PSResourceGet (Compress-PSResource, Publish-PSResource), which ships with PowerShell 7.6.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–30s
Visual: three gates — Analyze, Test, Package — and OpsKit 0.5 bouncing off the first (3 warnings).
Narration: one build script, three gates, the same for you and CI.
Shot 2 · 30–60s
Visual: coverage meter 29% → 100%; the Monitored bug caught by one red test out of 51.
Narration: coverage finds untested code; assertions find bugs.
Shot 3 · 60–90s
Visual: OpsKit.1.0.0.nupkg dropping into a folder repository; a tag v1.0.0 launching the workflow.
Narration: version, package, tag — OpsKit 1.0 is released.
or score ≥ 70% on the Quiz

Command cheat sheet

All Lesson 8 key points: debugging, static analysis, Pester 6 tests and mocks, coverage and exit codes, performance, signing and versions, CI, build and release
PowerShell 7.6 · Pester 6.2Copyable

1. Debugging

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 -Strict

2. PSScriptAnalyzer

Invoke-ScriptAnalyzer -Path ./src -Recurse -Settings ./PSScriptAnalyzerSettings.psd1
Invoke-ScriptAnalyzer -ScriptDefinition $code -IncludeRule PSAvoidUsing*
Get-ScriptAnalyzerRule -Severity Error
Invoke-ScriptAnalyzer ./x.ps1 -Fix          # 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!

3. Pester 6 structure

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

4. Assertions

$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 -Be

5. Mocking

Mock 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

6. Coverage, results, exit codes

$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)

7. Performance

(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)

8. Release

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

Integrated lab + final quiz

Run the OpsKit 1.0.0 release build end to end, break it in three different ways, and prove each gate catches its problem
about 25 minLocal onlyIntegrates M1–M8

Scenario

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.

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

Running tests from 9 files.
Starting code coverage.
[+] …\Get-OpsCloudInventory.Tests.ps1 1.26s (2 tests)
[+] …\Get-OpsConfig.Tests.ps1 395ms (6 tests)
[+] …\Get-OpsServer.Tests.ps1 390ms (9 tests)
[+] …\Invoke-OpsApi.Tests.ps1 613ms (6 tests)
[+] …\Invoke-OpsBackup.Tests.ps1 600ms (7 tests)
[+] …\Invoke-OpsHealthCheck.Tests.ps1 275ms (3 tests)
[+] …\OpsKit.Module.Tests.ps1 390ms (9 tests)
[+] …\Private.Tests.ps1 183ms (4 tests)
[+] …\Test-OpsEndpoint.Tests.ps1 398ms (5 tests)
Tests completed in 4.55s
Tests Passed: 51, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0
Processing code coverage result.
Covered 100% / 80%. 167 analyzed Commands in 9 Files.
Test: 51 passed, coverage 100% (threshold 80%).
==> Package
Package: C:\Users\labadmin\pslab\OpsKit\out\repo\OpsKit.1.0.0.nupkg (10808 bytes).
Build succeeded.
exit=0
2. Break a function (M3, M4): change -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.

3. Break the style (M2): put 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.
4. Lower coverage (M5): move 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.
5. Debug a failure (M1): while step 2's bug is in place, import the module, set 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.

6. Measure (M6): 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.
7. Release metadata (M7): check 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).
Acceptance criteria

Open-ended self-check

1. A test file passes in VS Code's test explorer but fails in CI with “Expected 12, but got 0”. Give the two most likely causes.

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.

2. Why does the OpsKit test suite define a default mock before filtered mocks?

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.

3. Your build is green but users report a crash. Which gate failed, and how do you change the process?

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.

4. When is Set-PSDebug -Trace 2 unsafe?

When the code handles secrets: ! SET lines print variable values into logs.

Sources and version notes

Version facts were checked on 2026-11-24 against the PowerShell Gallery, the Pester GitHub releases, Microsoft Learn and the GitHub API; command outputs were produced on PowerShell 7.6.10 with Pester 6.2.0 and PSScriptAnalyzer 1.25.0
Verification date 2026-11-24
TopicVerified resultSources (accessed 2026-11-24)
Pester versionsGallery: 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 pwshFind-PSResource Pester; Pester 6.2.0 release
Pester 6 changesShould-* 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 validation6.0.0 release notes; 6.1.0; 6.2.0; reproduced in this lesson
Pester behavior reproducedDiscovery-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 coverageActual runs (outputs in Modules 3–5)
PSScriptAnalyzer1.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+ argumentsOverview; Using PSScriptAnalyzer; actual runs
DebuggerBreakpoint 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 stringsabout_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.2GitHub PowerShell/vscode-powershell package.json; Using VS Code
PerformanceTimings in Module 6 from one Windows 11 machine (best of 3)Performance considerations; actual runs
Signing and language modesGet-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.nupkgUpdate-PSModuleManifest; Compress-PSResource; Prerelease versions; semver.org
GitHub Actionsactions/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 executedGitHub REST API releases; Workflow syntax

Video verification notes

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.

Voice narration notes

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.

Known limitations

  • Run environment: all “Actual output” blocks come from Windows 11 with PowerShell 7.6.10. Pester 6.2.0 and PSScriptAnalyzer 1.25.0 were saved to a folder (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.
  • Not executed (Expected output): creating a self-signed certificate and signing (would modify the certificate store), registering a folder repository and installing from it (would modify the user's PSResourceGet repository list), publishing to the PowerShell Gallery, running the GitHub Actions workflow, and the VS Code debugger UI. The console debugger sessions are real, driven through redirected standard input.
  • The OpsKit code is a compact re-creation of what Lessons 3–7 build (same function names and parameters); in particular Invoke-OpsHealthCheck is sequential here, and Get-OpsCloudInventory is a thin wrapper over Get-AzResource tested only with mocks.
  • Performance numbers are from one machine and one run of best-of-3 measurements; expect different absolute values.
  • The animations simplify the engine and Pester internals (mock proxy generation, discovery containers, GitHub's job scheduler).