PowerShell Lesson 5: Robust Scripts — Errors, Streams and Safe Change
Get-OpsServer, Get-OpsConfig, Test-OpsEndpoint); Lesson 4 packaged it as a real module, OpsKit v0.2 (OpsKit.psd1 / OpsKit.psm1, Public/ and Private/, published to a local repository). Until now OpsKit only read things. In this lesson it starts to change things, which is where error handling stops being optional: OpsKit v0.3 adds Invoke-OpsBackup (zip ~/pslab/data, keep the newest 7, retry locked files, JSON-lines log, full -WhatIf support), Remove-OpsBackup and a reusable Invoke-OpsRetry. If you know Bash, think of this lesson as the PowerShell answer to set -euo pipefail, trap, 2>&1 and “dry-run” flags — with more precision and a few traps of its own.- Classify any error as non-terminating, statement-terminating or script-terminating, predict what runs next — this lesson's core animation — and read an
ErrorRecord(Exception,CategoryInfo,FullyQualifiedErrorId,TargetObject,InvocationInfo,ScriptStackTrace) withGet-Error. - Explain why
try { Get-Item missing.txt }catches nothing, fix it with-ErrorAction Stop, write typed catch blocks andfinally, and choose betweenthrow,Write-Errorand$PSCmdlet.ThrowTerminatingError(). - Handle native programs correctly:
$LASTEXITCODE,$?, stderr records, and$PSNativeCommandUseErrorActionPreferencetogether with$ErrorActionPreference = 'Stop'— including programs such as robocopy whose non-zero codes mean success. - Route the six streams with
2>&1,3>,*>,6>&1and>$null; useWrite-Verbose/-Debug/-Warning/-Information, preference variables and-XxxVariableparameters; and know whyWrite-Hostis stream 6. - Turn on
Set-StrictMode -Version Latestand reproduce what it catches (uninitialized variables, missing properties — even hashtable keys — method-call syntax, out-of-range indexes); write guard clauses, validation attributes and correct$nullcomparisons. - Implement
SupportsShouldProcesscorrectly:$PSCmdlet.ShouldProcess(),ConfirmImpactvs$ConfirmPreference, how-WhatIfpropagates — and the verified case where it does not reachCompress-Archive. - Write
Invoke-OpsRetrywith exponential backoff and jitter that retries only transient, terminating errors; bound waits withWait-Job -Timeout, cancellation tokens and web-cmdlet timeouts; write JSON-lines logs; and know whatStart-Transcriptmisses. - Ship OpsKit v0.3:
Invoke-OpsBackup+Remove-OpsBackupwith rotation,-WhatIf, retries and logs; a nightly wrapper with meaningful exit codes; and a failure-injection script that proves every error path.
1-Hour Time Allocation
| # | Time | Module | Core Content | Animation / Interactive | Lab (~/pslab) |
|---|---|---|---|---|---|
| 0 | Before Class | Prep: failure scenario scripts | OpsKit v0.2 → v0.3 layout, $env:OPSKIT_HOME, scripts/Show-ErrorKinds.ps1, a clean tmp/ | Warm-up questions from Lesson 4 | Import OpsKit 0.3.0 from ~/pslab/OpsKit |
| 1 | 00–06 | Error model | Non-terminating, statement-terminating, script-terminating; $Error; ErrorRecord anatomy; Get-Error; $? | core animation: what happens to an error | Dissect a real ErrorRecord |
| 2 | 06–13 | try / catch | -ErrorAction, $ErrorActionPreference, typed catch, finally, throw vs Write-Error vs ThrowTerminatingError, trap, -ErrorVariable | Which catch block runs? | Read-Config with three typed catches |
| 3 | 13–21 | Native commands | $LASTEXITCODE, $?, stderr as ErrorRecord, NativeCommandExitException, robocopy codes | Native exit code router | git and cmd failures, the robocopy trap |
| 4 | 21–28 | Streams | Streams 1–6, redirection operators, preference variables, -InformationVariable, Write-Host = stream 6 | Stream router | Capture each stream separately |
| 5 | 28–35 | Strict mode | Set-StrictMode -Version Latest, guard clauses, validation attributes, $null -eq, Stop at boundaries | Strict-mode checker | Reproduce four silent bugs, then catch them |
| 6 | 35–42 | Safe change | SupportsShouldProcess, ShouldProcess(), ConfirmImpact, $ConfirmPreference, $WhatIfPreference, propagation, idempotency | ShouldProcess decision path | Prove where -WhatIf does and does not flow |
| 7 | 42–50 | Retries, timeouts, logs | Invoke-OpsRetry (backoff + jitter), Wait-Job -Timeout, CancellationToken, -TimeoutSec vs -OperationTimeoutSeconds, JSON lines, transcripts | Retry timeline | Retry, time out, log |
| 8 | 50–60 | OpsKit v0.3 | Invoke-OpsBackup, Remove-OpsBackup, rotation, partial-archive cleanup, nightly wrapper exit codes | Backup run path + troubleshooting tree | Back up, rotate, lock a file, read the log |
| — | After Class | Cheat sheet · Integrated lab | Test-OpsFailure.ps1: inject 8 failures and check exit codes, archives and log events | Final quiz (12 questions) | All 8 scenarios pass |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Classify errors and read ErrorRecords | ✓ | ✓ | ✓ | · | ✓ | · | · | ✓ | $Error[0], Get-Error, FullyQualifiedErrorId | M1 |
| Catch the right errors | ✓ | ✓ | ✓ | · | ✓ | · | ✓ | ✓ | -ErrorAction Stop, catch [Type], finally | M2, integrated lab |
| Raise errors from your own commands | · | ✓ | · | · | ✓ | · | ✓ | ✓ | throw, Write-Error, $PSCmdlet.ThrowTerminatingError() | M2, M8 |
| Native exit codes | ✓ | · | ✓ | ✓ | · | · | · | ✓ | $LASTEXITCODE, $PSNativeCommandUseErrorActionPreference | M3, integrated lab |
| Streams and redirection | · | ✓ | ✓ | ✓ | · | ✓ | ✓ | · | 2>&1, *>, -InformationVariable, Write-Verbose | M4 |
| Defensive coding and strict mode | · | · | · | · | ✓ | ✓ | · | ✓ | Set-StrictMode, [ValidateRange()], $null -eq $x | M5, M8 |
| Safe change: -WhatIf / -Confirm / idempotency | · | · | · | · | · | ✓ | · | ✓ | SupportsShouldProcess, ShouldProcess(), ConfirmImpact | M6, M8, integrated lab |
| Retries, timeouts and logs | · | · | · | ✓ | · | · | ✓ | ✓ | Invoke-OpsRetry, Wait-Job -Timeout, ConvertTo-Json -Compress | M7, M8, integrated lab |
Excluded from this lesson (and where to learn it)
| Topic | Why not in this lesson | Where to learn it |
|---|---|---|
Errors from remote computers (Invoke-Command per-computer errors, PSComputerName), job error handling in depth, ForEach-Object -Parallel errors | Needs remoting and runspaces first | Lesson 6: Remoting, Jobs and Parallel Administration |
HTTP error handling: status codes, -SkipHttpErrorCheck, -MaximumRetryCount, throttling (429) and Retry-After | Belongs to REST/cloud automation; this lesson only previews web timeouts | Lesson 7 (Invoke-OpsApi reuses Invoke-OpsRetry) |
Testing error paths with Pester (Should -Throw / Should-Throw), PSScriptAnalyzer rules such as PSShouldProcess, the debugger | Quality tooling | Lesson 8 |
Classes and custom exception types (class OpsException : Exception) | Rarely needed: an ErrorRecord with a good FullyQualifiedErrorId is usually enough | Everything you wanted to know about exceptions |
| Windows event log / syslog / OpenTelemetry shipping | Platform-specific; JSON lines are the portable first step | Your observability platform's docs |
How to use these materials
Principles · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. The Module 1 animation (“what happens to an error”) is the mental model for the whole lesson; replay it whenever a later output surprises you.
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).
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.
$PSNativeCommandUseErrorActionPreference became a mainstream (non-experimental) feature in 7.4 and defaults to $false. Since 7.2, stderr from native programs no longer sets $? to $false or triggers $ErrorActionPreference = 'Stop' — a big difference from Windows PowerShell 5.1, where 2>&1 on a native command could stop a script. Get-Error exists only in 7.x. Compress-Archive comes from Microsoft.PowerShell.Archive 1.2.7 on the lab machine (a script module) — that detail matters in Module 6.Module 0 · Prep: failure scenario scripts
$env:OPSKIT_HOME switch that lets tests run against a throw-away copy instead of your real backups- Lessons 1–4:
~/pslab/datagenerated byNew-LabData.ps1, and~/pslab/OpsKitas the v0.2 script module (OpsKit.psd1,OpsKit.psm1,Public/,Private/). - PowerShell 7.4 or later (7.6 recommended).
gitis used for one native-command example; any installed version works. - Windows only for two examples (
cmd /c,robocopy); Linux/macOS equivalents are given (sh -c 'exit 3',rsync).
Warm-up: answer from memory (30 seconds)
1. In OpsKit v0.2, what decides which functions a caller can see: the .psm1 or the .psd1?
Both filter: Export-ModuleMember in the .psm1 exports, and FunctionsToExport in the manifest narrows that further (and enables fast auto-loading discovery). Private helpers stay invisible but are callable inside the module.
2. A function in a module sets $ErrorActionPreference = 'Stop' at the top of the .psm1. Does the caller's session change?
No. The module has its own session state; the variable lives in the module scope. Verified below in Module 6's lab: after Import-Module, the caller still has Continue.
3. From Lesson 1: which pwsh switch passes a script's exit 3 to the caller unchanged?
pwsh -File. -Command reports only 0/1 unless you append ; exit $LASTEXITCODE. This lesson builds on that: a nightly job is only as good as its exit code.
Step 1: the OpsKit v0.3 layout
v0.3 adds three public commands and two private helpers. The manifest version goes to 0.3.0; nothing else in the v0.2 structure changes. Full source of every new file is in Module 8.
| File | Status | Purpose |
|---|---|---|
OpsKit.psd1 | changed | ModuleVersion = '0.3.0'; FunctionsToExport lists the six public commands |
OpsKit.psm1 | changed | Adds Set-StrictMode -Version Latest and $ErrorActionPreference = 'Stop' at module scope (Module 5) |
Public/Get-OpsConfig.ps1 | changed | Raises OpsKit.ConfigNotFound with ThrowTerminatingError (Module 2) |
Public/Invoke-OpsRetry.ps1 | new | Generic retry with backoff and jitter (Module 7) |
Public/Invoke-OpsBackup.ps1, Public/Remove-OpsBackup.ps1 | new | Backup + rotation (Module 8) |
Private/Write-OpsLog.ps1, Private/Resolve-OpsPath.ps1 | new | JSON-lines log; maps ~/pslab/… from the config to the OpsKit root |
Set-Location ~/pslab
Import-Module ./OpsKit/OpsKit.psd1 -Force
Get-Module OpsKit | Format-Table Name, Version, ModuleType -AutoSize
Get-ChildItem ./OpsKit -Recurse -File | ForEach-Object { $_.FullName.Substring($PWD.Path.Length + 1) }
Name Version ModuleType ---- ------- ---------- OpsKit 0.3.0 Script OpsKit\OpsKit.psd1 OpsKit\OpsKit.psm1 OpsKit\Private\Resolve-OpsPath.ps1 OpsKit\Private\Write-OpsLog.ps1 OpsKit\Public\Get-OpsConfig.ps1 OpsKit\Public\Get-OpsServer.ps1 OpsKit\Public\Invoke-OpsBackup.ps1 OpsKit\Public\Invoke-OpsRetry.ps1 OpsKit\Public\Remove-OpsBackup.ps1 OpsKit\Public\Test-OpsEndpoint.ps1
You can build v0.3 step by step while reading Modules 6–8, or paste all files from Module 8 now. If you installed v0.2 from your local repository in Lesson 4, import by path (as above) during development so you test the files you are editing, not the installed copy; republishing is part of Lesson 4's workflow.
Step 2: $env:OPSKIT_HOME — a root you can point at a sandbox
The config file says Backup.Destination = '~/pslab/backups'. From v0.3, OpsKit resolves every ~/pslab/… path through Resolve-OpsPath, which uses $env:OPSKIT_HOME if it is set and ~/pslab otherwise. Tests (the integrated lab) set it to ~/pslab/tmp/fi, so failure injection can lock, corrupt and delete files without touching your real backups. Production keeps the default.
$env:OPSKIT_HOME # empty → OpsKit uses ~/pslab # In a test only: $env:OPSKIT_HOME = "$HOME/pslab/tmp/fi" (child pwsh processes inherit it)
All outputs in this lesson were produced with the OpsKit root pointing at the lab folder; paths are shown as C:\Users\labadmin\pslab\….
Step 3: a script that produces all three kinds of error
Save as ~/pslab/scripts/Show-ErrorKinds.ps1. Module 1 runs it.
'start' [int]'abc' # statement-terminating: only this statement stops 'after conversion error' Get-Item ./nope.txt # non-terminating: error written, script continues 'after Get-Item' throw 'boom' # script-terminating: the whole script stops 'never printed'
Step 4: clean scratch space
New-Item -ItemType Directory -Path ~/pslab/tmp, ~/pslab/backups -Force | Out-Null Get-ChildItem ~/pslab/tmp -File | Remove-Item -WhatIf # look first … Get-ChildItem ~/pslab/tmp -File | Remove-Item # … then delete
The -WhatIf line is a habit this lesson wants to build: preview any delete whose target comes from a wildcard or a pipeline.
Environment self-check checklist
~/pslab (and the integrated lab only inside ~/pslab/tmp/fi). Never point -Destination or $env:OPSKIT_HOME at a folder you care about while experimenting. Remove-OpsBackup only matches pslab-data-*.zip. Cleanup at the end: Remove-Item ~/pslab/backups, ~/pslab/tmp/fi -Recurse -Force (Lessons 6–8 do not need the archives).Module 1 · The Error Model: terminating vs non-terminating, $Error and ErrorRecord
- Name the three kinds of error — non-terminating, statement-terminating, script-terminating — and predict which lines still run after each (core animation).
- Read the parts of an
ErrorRecord:Exception,CategoryInfo,FullyQualifiedErrorId,TargetObject,InvocationInfo,ScriptStackTrace. - Use
$Error,$?andGet-Error, and know that-ErrorAction Ignoreis the only setting that keeps an error out of$Error. - Compare with Bash: there is no single “exit status”; there are objects, kinds and preferences.
What: three kinds of error
| Kind | Typical sources | What stops | Caught by try/catch? |
|---|---|---|---|
| Non-terminating | Most cmdlets when one input item fails: Get-Item a, missing, b, Remove-Item on a locked file; Write-Error | Nothing — the error is written to stream 2 and $Error, the command continues with the next item, the script continues | No, unless it is promoted with -ErrorAction Stop or $ErrorActionPreference = 'Stop' |
| Statement-terminating | .NET exceptions in expressions ([int]'abc', 1/$zero, method calls), parameter binding errors, command not found, $PSCmdlet.ThrowTerminatingError() | The current statement (pipeline). The next statement runs | Yes |
| Script-terminating | throw; any error promoted by -ErrorAction Stop / $ErrorActionPreference = 'Stop'; parse errors | Everything up the call stack — functions, scripts, the whole command line — until a try/catch or trap | Yes |
Why: an error is an object, not a number
Bash has one integer per command and set -e to act on it. PowerShell commands process many objects, and one bad item (one missing file out of a thousand) should not kill the other 999 — hence non-terminating errors by default. The price: a script happily continues after errors unless you say otherwise. Every error is a System.Management.Automation.ErrorRecord:
| Property | What it tells you | Example (missing file) |
|---|---|---|
Exception | The .NET exception: type, message, inner exception, stack | ItemNotFoundException |
CategoryInfo | Category (ObjectNotFound, InvalidArgument, PermissionDenied …), target, activity, reason | ObjectNotFound: (…nope.txt:String) [Get-Item], ItemNotFoundException |
FullyQualifiedErrorId | A stable id, ErrorId,CommandType — the thing to match on, not the message (messages are localized) | PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand |
TargetObject | The input item that failed | the path |
InvocationInfo | Which command, script, line and position | MyCommand = Get-Item |
ScriptStackTrace | The PowerShell call stack (functions and scripts) | at Get-Thing … at Invoke-Outer … |
How: $Error, $? and Get-Error
$Erroris anArrayListof the last errors in the session, newest first ($Error[0]), capped by$MaximumErrorCount(256). It is global: functions and modules add to the same list.$Error.Clear()empties it.$?is$falseif the last statement wrote any error (including non-terminating ones) — but only the last statement.Get-Error(7.x) shows the newest error (or-Newest N) with every nested property expanded;$ErrorView = 'DetailedView'does similar for display.-ErrorAction SilentlyContinuehides the message but still records the error in$Error;-ErrorAction Ignorerecords nothing (verified below).
When: which kind will I get?
Ask: “Did a cmdlet report a problem with one item, or did the engine fail to run a statement?” Item problems are non-terminating. Engine/expression failures are statement-terminating. throw and anything with Stop are script-terminating. If you cannot tell, test it: put the line in a try and see whether catch runs.
try catches all errors” — not non-terminating ones (Module 2). ② “An error means the script stopped” — for non-terminating and statement-terminating errors, the next line runs. ③ “$? tells me if my script failed” — it reflects only the last statement. ④ “SilentlyContinue means no trace” — the error is still in $Error. ⑤ “Match on the message text” — messages are localized and change; match on FullyQualifiedErrorId or the exception type. ⑥ “A throw inside a function only stops the function” — it stops every caller up to the nearest try.Diagram: anatomy of an ErrorRecord
Flowchart: what happens to an error
Core animation: what happens to an error
Choose an error and step through: its kind, whether a preference applies, whether it lands in $Error and on stream 2, whether a try/catch sees it, and what runs next. Every scenario's log text is real 7.6.10 output from this lesson.
WriteError(); the engine checks the effective ErrorActionPreference (the -ErrorAction argument sets a local $ErrorActionPreference for that command) and, for Stop, throws an ActionPreferenceStopException carrying the original record. Terminating errors are .NET exceptions (RuntimeException and friends) that unwind the stack until the engine finds a catch or trap; without one, a statement-terminating error ends only its statement, while a script-terminating one (throw, Stop) ends the whole script or command line. Native programs never raise errors by exit code unless Module 3's preference is on.Command table
| Command / variable | Purpose | Notes |
|---|---|---|
$Error[0] | Newest error | Global list, newest first; $Error.Count, $Error.Clear() |
$? | Did the last statement succeed? | $false after any error in that statement, including non-terminating |
Get-Error [-Newest N] | Expand an error completely | 7.x only; pipe an ErrorRecord in: $e | Get-Error |
$ErrorView | How errors are displayed | ConciseView (default), NormalView, DetailedView |
$e.Exception.GetType().FullName | Exception type for catch [Type] | Check .InnerException too |
$e.FullyQualifiedErrorId | Stable id | Branch on it in automation |
$e.ScriptStackTrace | Where in your scripts | Log it for unexpected errors |
$MaximumErrorCount | Size of $Error | Default 256 |
$Error.Clear() Get-Item ./data/nope.txt $Error.Count $e = $Error[0] $e.GetType().FullName $e.Exception.GetType().FullName $e.CategoryInfo.ToString() $e.FullyQualifiedErrorId $e.TargetObject $e.InvocationInfo.MyCommand.Name
Get-Item: Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist. 1 System.Management.Automation.ErrorRecord System.Management.Automation.ItemNotFoundException ObjectNotFound: (C:\Users\labadmin\pslab\data\nope.txt:String) [Get-Item], ItemNotFoundException PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand C:\Users\labadmin\pslab\data\nope.txt Get-Item
How to verify: the id has two parts: PathNotFound (the error id chosen by the cmdlet author) and the command's class. Common mistake: writing if ($Error) to detect failure in a script — $Error also contains errors from earlier commands and modules; use $?, -ErrorVariable or try/catch. Production use: log FullyQualifiedErrorId, the exception type and TargetObject as separate fields (Module 7).
ScriptStackTrace: who called whom
function Get-Thing { [CmdletBinding()] param() Get-Item ./data/nope.txt -ErrorAction Stop }
function Invoke-Outer { Get-Thing }
try { Invoke-Outer } catch { $_.ScriptStackTrace }
at Get-Thing, <No file>: line 1 at Invoke-Outer, <No file>: line 1 at <ScriptBlock>, <No file>: line 1
SilentlyContinue vs Ignore
$Error.Clear() Get-Item ./data/nope.txt -ErrorAction SilentlyContinue; $? $Error.Count Get-Item ./data/nope.txt -ErrorAction Ignore; $? $Error.Count
False 1 False 1
Both report $? = False; only SilentlyContinue added an entry (the count stayed 1 after Ignore). Ignore is not allowed as a value of $ErrorActionPreference, only as an -ErrorAction argument.
Get-Error (abridged)
Get-Item ./data/nope.txt -ErrorAction SilentlyContinue Get-Error -Newest 1
Exception :
Type : System.Management.Automation.ItemNotFoundException
ErrorRecord :
…
ItemName : C:\Users\labadmin\pslab\data\nope.txt
SessionStateCategory : Drive
TargetSite :
Name : ExpandMshGlobPath
DeclaringType : [System.Management.Automation.LocationGlobber]
…
Message : Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist.
Source : System.Management.Automation
HResult : -2146233087
StackTrace :
at System.Management.Automation.LocationGlobber.ExpandMshGlobPath(…)
…
at Microsoft.PowerShell.Commands.GetItemCommand.ProcessRecord()
TargetObject : C:\Users\labadmin\pslab\data\nope.txt
CategoryInfo : ObjectNotFound: (C:\Users\labadmin\pslab\data\nope.txt:String) [Get-Item], ItemNotFoundException
FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
InvocationInfo :
MyCommand : Get-Item
ScriptLineNumber : 1
OffsetInLine : 1
HistoryId : 1
Line : Get-Item ./data/nope.txt -ErrorAction SilentlyContinue
…
ScriptStackTrace : at <ScriptBlock>, <No file>: line 1
Goal: See all three kinds of error in one script and prove which lines run. Environment: ~/pslab, PowerShell 7.6. Cost: none; nothing is changed on disk.
Set-Location ~/pslab pwsh -NoProfile -File ./scripts/Show-ErrorKinds.ps1; "exit=$LASTEXITCODE"
start
InvalidArgument: C:\Users\labadmin\pslab\scripts\Show-ErrorKinds.ps1:2
Line |
2 | [int]'abc' # statement-terminating: only this statement stop …
| ~~~~~~~~~~
| Cannot convert value "abc" to type "System.Int32". Error: "The input string 'abc' was not in a correct format."
after conversion error
Get-Item: C:\Users\labadmin\pslab\scripts\Show-ErrorKinds.ps1:4
Line |
4 | Get-Item ./nope.txt # non-terminating: error written, script continue …
| ~~~~~~~~~~~~~~~~~~~
| Cannot find path 'C:\Users\labadmin\pslab\nope.txt' because it does not exist.
after Get-Item
Exception: C:\Users\labadmin\pslab\scripts\Show-ErrorKinds.ps1:6
Line |
6 | throw 'boom' # script-terminating: the whole script stops
| ~~~~~~~~~~~~
| boom
exit=1
“after conversion error” and “after Get-Item” printed; “never printed” did not. pwsh -File turned the unhandled throw into exit code 1. Note how ConciseView names the category (InvalidArgument:) for expression errors and the command (Get-Item:) for cmdlet errors.
& ./scripts/Show-ErrorKinds.ps1; 'same line, after the script'
Result on 7.6.10: the same three errors, and 'same line, after the script' is not printed — a script-terminating error ends the whole command line (or the whole calling script), not just the called script. Type the next command at a new prompt and it runs normally.
$Error.Clear() … MyCommand.Name) and write down the FullyQualifiedErrorId. Then do the same for [int]'abc':
[int]'abc' $Error[0].FullyQualifiedErrorId; $Error[0].Exception.GetType().Name; $Error[0].CategoryInfo.Category
InvalidArgument: Cannot convert value "abc" to type "System.Int32". Error: "The input string 'abc' was not in a correct format." InvalidCastFromStringToInteger RuntimeException InvalidArgument
The exception type is the generic RuntimeException; the specific information is in the id InvalidCastFromStringToInteger — another reason to match on the id.
$Error.Clear() (nothing on disk to remove).Case 1: “the job is green, but half the files were never copied”
Problem: A sync script ran Copy-Item $files -Destination \\nas\share every night and reported success for weeks; an audit found 200 missing files. Root cause: files locked by another process produced non-terminating errors; the script continued and ended with exit 0. Nobody read the red text in the scheduler's output. Fix: make the boundary strict — $ErrorActionPreference = 'Stop' plus try/catch around each file, count failures, and exit non-zero if any failed; log TargetObject for each failure (Module 7).
Case 2: an alert keyed on English error text
Problem: A monitoring rule matched "Cannot find path" in logs; on servers with a German UI it never fired. Root cause: exception messages are localized. Fix: log and match FullyQualifiedErrorId (PathNotFound,…) and the exception type — both are culture-independent.
Case 3: “we checked $Error and the deployment always failed”
Problem: A deployment script ended with if ($Error.Count -gt 0) { exit 1 } and failed every run in the build agent. Root cause: a module imported at the start wrote a harmless, swallowed error into the global $Error list. Fix: never use $Error as a success signal; capture errors from the commands you care about with -ErrorVariable or try/catch.
Common errors and fixes
My catch block never runs although red text appears
Cause: the error is non-terminating.
try { Get-Item ./data/nope.txt -ErrorAction Stop } catch { "caught: $($_.FullyQualifiedErrorId)" }
Fix: add -ErrorAction Stop to the command, or set $ErrorActionPreference = 'Stop' at the script boundary (Module 2).
The script continued after an error and printed “done”
Cause: non-terminating or statement-terminating error without a handler. Fix: decide for each step whether a failure must stop the run; if yes, use Stop + try/catch and exit with a non-zero code.
I cannot tell which line inside my module failed
$Error[0].ScriptStackTrace $Error[0].InvocationInfo.PositionMessage Get-Error -Newest 1
Fix: log ScriptStackTrace for unexpected errors; ConciseView only shows the outermost position.
$Error is full of old errors and I can't find mine
Fix: $Error.Clear() before an experiment, or capture with -ErrorVariable myErr so you get only that command's errors.
1. Print the error id and the failing target for every error currently in $Error, newest first.
$Error | ForEach-Object { '{0} -> {1}' -f $_.FullyQualifiedErrorId, $_.TargetObject }2. Prove that Get-Item a, missing, b still returns two items.
$r = Get-Item ./data/servers.csv, ./data/nope.txt, ./data/access.log $r.Name
Get-Item: Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist. servers.csv access.log
A colleague's cleanup script runs Get-ChildItem $logDir | Remove-Item and then writes “cleanup complete” to a status file. Some logs are locked by the web server. What does the status file say, what does the disk look like, and what would you change?
The status file says “cleanup complete” — Remove-Item wrote one non-terminating error per locked file and moved on, and the next statement ran. The disk still holds the locked files. Change: collect errors with -ErrorVariable rmErr (or Stop + per-file try/catch), write a status that includes $rmErr.Count and the TargetObject list, and exit non-zero (or retry later, Module 7) when the count is above zero. Decide explicitly whether a locked log is a failure or an expected skip.
Verified teaching videos
Official documentation
- Everything you wanted to know about exceptions · Get-Error
- about_Automatic_Variables ($Error, $?) · about_Preference_Variables ($ErrorView)
Video storyboard (about 90 seconds)
These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.
Visual: three files flow into Get-Item; the middle one turns red, the other two still come out.
Narration: a non-terminating error reports one bad item and keeps going.
Visual: a script listing; a red bar crosses one line ([int]'abc') and the next line lights up; then a throw line and every remaining line greys out.
Narration: statement-terminating stops one statement; script-terminating stops everything up to the nearest catch.
Visual: an ErrorRecord explodes into six labelled cards (Exception, CategoryInfo, FullyQualifiedErrorId …).
Narration: an error is an object. Match on the id, not the message.
Visual: a green “success” badge on a scheduler, then a magnifier showing red text in the log.
Narration: errors that do not stop the script are the ones that hurt you in production.
Module 2 · -ErrorAction, try / catch / finally, typed catch, throw vs Write-Error
- Explain why
try { Get-Item missing }does not reachcatch, and fix it two ways (-ErrorAction Stop,$ErrorActionPreference). - Write ordered, typed
catchblocks and afinallythat always runs. - Choose between
throw(script-terminating),Write-Error(non-terminating) and$PSCmdlet.ThrowTerminatingError()(statement-terminating) in advanced functions. - Use
-ErrorVariable(and+nameto append) and recognisetrapin older code.
What: the ErrorAction values
| Value | Shows the error? | Adds to $Error? | Continues? | Typical use |
|---|---|---|---|---|
Continue (default) | Yes | Yes | Yes | Interactive work |
SilentlyContinue | No | Yes | Yes | “Not found is fine”, e.g. Get-Command x -ErrorAction SilentlyContinue |
Ignore | No | No | Yes | Same, without polluting $Error; only as a parameter value |
Stop | Via catch | Yes | No — script-terminating | Anything inside try; script boundaries |
Inquire | Prompts | Yes | User decides | Debugging only; fails under -NonInteractive |
Break | Enters the debugger | Yes | — | Debugging (7.x) |
-ErrorAction (a common parameter of every cmdlet and advanced function) overrides $ErrorActionPreference for that one command. Neither affects statement-terminating errors that are not produced by a command (parameter binding errors, .NET exceptions) — with one quirk: $ErrorActionPreference = 'SilentlyContinue' also hides statement-terminating errors (verified below). Never set it globally.
Why: try only sees terminating errors
A non-terminating error is just a record written to stream 2; there is no exception to catch. -ErrorAction Stop turns it into an exception at the source, and the catch block receives the original ErrorRecord, so typed catch still works: catch [System.Management.Automation.ItemNotFoundException] catches a missing file even though the engine wrapped it in an ActionPreferenceStopException on the way.
How: raising errors from your own functions
| You write | Kind for the caller | Caller's next statement (no try) | Use it when |
|---|---|---|---|
Write-Error 'msg' / $PSCmdlet.WriteError($rec) | Non-terminating | Runs; your function also keeps running | One input item failed; others may succeed |
$PSCmdlet.ThrowTerminatingError($rec) | Statement-terminating | Runs (even on the same line) | Your command cannot do its job at all (missing config). Best practice in advanced functions: the error looks like it came from your command, not from a line inside it |
throw 'msg' / throw $rec | Script-terminating | Does not run — the whole script stops unless caught | Scripts and internal code; when anything after it would be dangerous |
All three verified on 7.6.10 in the Commands tab. The difference between the last two surprises most people: a module that uses ThrowTerminatingError (as cmdlets do) does not stop a caller's script by itself — the caller must use -ErrorAction Stop, $ErrorActionPreference = 'Stop' or try/catch. That is the root of Module 8's “script reported success” troubleshooting tree.
When: catch order, finally, trap
- Catch blocks are tested top to bottom; the first whose type matches (including base types) wins. Put specific types first and a bare
catchlast. finallyruns after try (and catch) whether or not an error occurred — and even when the catch rethrows or the user presses Ctrl+C. Use it to close files, pop locations, dispose handles.trapis the pre-v2 mechanism: a handler for the whole scope;continueresumes after the failing statement,breakrethrows. You will meet it in old scripts; write new code with try/catch.- Inside
catch,$_(or$PSItem) is the ErrorRecord; a barethrowrethrows it unchanged.
catch without -ErrorAction Stop works for cmdlets” — only for errors that are already terminating. ② “Stop in my script is enough, so my module needs no error policy” — a module cannot know how its callers set preferences; it should decide explicitly (OpsKit sets Stop at module scope and raises errors with stable ids). ③ “throw in a function just returns an error” — it stops every caller. ④ “catch [Exception] first is fine” — it swallows everything below it. ⑤ “-ErrorAction SilentlyContinue on Get-Item -Nope hides the error” — parameter binding errors are not affected (verified).Diagram: try / catch / finally control flow
Diagram: three ways to fail from an advanced function
Which catch block runs?
The function Read-Config (Commands tab) reads a JSON file inside try with three catch blocks and a finally. Choose an input and watch which block handles it.
$exception -is [Type] for each listed type (one clause may list several types separated by commas). For errors promoted by Stop, the test is done against the original exception inside the ErrorRecord, which is why ItemNotFoundException matches. finally is compiled as a .NET finally block, so it runs on every exit path.Command table
| Syntax | Purpose | Notes |
|---|---|---|
-ErrorAction Stop / -EA Stop | Promote this command's errors | The usual partner of try |
$ErrorActionPreference = 'Stop' | Promote all command errors in this scope | Set at the top of scripts, not in your profile |
catch [T1], [T2] { } | Typed catch | Full .NET type names; specific first |
finally { } | Cleanup | Runs on every path |
throw (inside catch) | Rethrow the current error | Keeps the original ErrorRecord |
$PSCmdlet.ThrowTerminatingError($rec) | Fail an advanced function | Statement-terminating for the caller |
-ErrorVariable ev / +ev | Capture this command's errors | No $ in the name; + appends |
trap [T] { …; continue } | Scope-wide handler (legacy) | Prefer try/catch |
try { Get-Item ./data/nope.txt; 'try block finished' } catch { "caught: $_" }
try { Get-Item ./data/nope.txt -ErrorAction Stop; 'not reached' } catch { "caught: $($_.Exception.GetType().Name)" }
Get-Item: Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist. try block finished caught: ItemNotFoundException
How to verify: the first try “finished” — the catch never ran. Common mistake: believing the red text means the catch handled it. Production use: every command whose failure should change control flow gets -ErrorAction Stop, or the script sets the preference at the top.
Typed catch blocks and finally
function Read-Config([string]$Path) {
try {
$raw = Get-Content -LiteralPath $Path -Raw -ErrorAction Stop
$raw | ConvertFrom-Json -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
"missing file: $Path"
}
catch [System.ArgumentException] {
"bad JSON ($($_.Exception.GetType().Name))"
}
catch {
"other: $($_.Exception.GetType().FullName)"
}
finally {
"finally ran for $Path"
}
}
Read-Config ./data/nope.json
Read-Config ./data/servers.csv
missing file: ./data/nope.json finally ran for ./data/nope.json bad JSON (ArgumentException) finally ran for ./data/servers.csv
ConvertFrom-Json reports invalid input as System.ArgumentException on 7.6.10 — check the type on your version with $_.Exception.GetType().FullName in a bare catch before writing a typed one. Note that finally output is part of the function's output: in a function that returns data, write cleanup in finally but don't emit values from it.
The preference variable
$ErrorActionPreference = 'Stop'
try { Get-Item ./data/nope.txt; 'not reached' } catch { "caught with preference: $($_.FullyQualifiedErrorId)" }
$ErrorActionPreference = 'Continue'
caught with preference: PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
Write-Error vs ThrowTerminatingError vs throw (in a script)
function Test-WError { [CmdletBinding()] param() Write-Error 'written'; 'Test-WError kept going' }
function Test-TTE { [CmdletBinding()] param()
$err = [System.Management.Automation.ErrorRecord]::new(
[System.IO.FileNotFoundException]::new('config missing'), 'OpsKit.ConfigMissing',
[System.Management.Automation.ErrorCategory]::ObjectNotFound, './opskit.config.psd1')
$PSCmdlet.ThrowTerminatingError($err)
'not reached'
}
Test-WError; 'caller after Test-WError'
Test-TTE; 'caller after Test-TTE (same line)'
'next line after Test-TTE'
Test-WError -ErrorAction Stop; 'caller after Test-WError -EA Stop'
'next line'
Test-WError: written Test-WError kept going caller after Test-WError Test-TTE: config missing caller after Test-TTE (same line) next line after Test-TTE Test-WError: written
The caller's -ErrorAction Stop turned the non-terminating Write-Error into a script-terminating error: neither “caller after …” nor “next line” ran, and the script exited with 1. With function Test-Throw { [CmdletBinding()] param() throw 'thrown' }, Test-Throw; 'caller after' printed only Exception: thrown and exit code 1.
Catching by type and by id
try { Test-Nothing } catch { $_.Exception.GetType().Name }
try { Test-TTE } catch { "$($_.FullyQualifiedErrorId) | $($_.CategoryInfo.Category) | $($_.Exception.GetType().Name)" }
try { throw [System.TimeoutException]::new('slow') } catch [System.TimeoutException] { "typed: $($_.Exception.Message)" }
CommandNotFoundException OpsKit.ConfigMissing,Test-TTE | ObjectNotFound | FileNotFoundException typed: slow
-ErrorVariable and trap
Get-Item ./data/servers.csv, ./data/nope1, ./data/nope2 -ErrorAction SilentlyContinue -ErrorVariable ev |
Select-Object -ExpandProperty Name
$ev.Count
$ev | ForEach-Object { $_.TargetObject | Split-Path -Leaf }
Get-Item ./data/nope3 -ErrorAction SilentlyContinue -ErrorVariable +ev
$ev.Count
function Invoke-WithTrap {
trap [System.DivideByZeroException] { "trap: $($_.Exception.Message)"; continue }
'before'
$z = 0; 1 / $z
'after (trap used continue)'
}
Invoke-WithTrap
servers.csv 2 nope1 nope2 3 before trap: Attempted to divide by zero. after (trap used continue)
Two quirks worth knowing
Get-Item ./data -Nope -ErrorAction SilentlyContinue; "binding error not suppressed: ?=$?" $ErrorActionPreference = 'SilentlyContinue' [int]'abc'; "conversion error hidden by the preference variable, ?=$?" $ErrorActionPreference = 'Continue'
Get-Item: A parameter cannot be found that matches parameter name 'Nope'. binding error not suppressed: ?=False conversion error hidden by the preference variable, ?=False
Goal: Make a config reader fail the right way for each kind of bad input. Environment: ~/pslab. Cost: none.
Read-Config from the Commands tab and call it with the three inputs (missing, CSV, valid JSON). Confirm “finally ran” appears for every call.-ErrorAction Stop from the Get-Content line and call Read-Config ./data/nope.json again. Predict, then check: the red Get-Content error appears, $raw is $null, and ConvertFrom-Json receives nothing — the function returns only “finally ran …”. That silent empty result is worse than an error.function Read-OpsJson {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Path)
try {
Get-Content -LiteralPath $Path -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
}
catch {
$PSCmdlet.ThrowTerminatingError($_) # re-raise as OUR error, statement-terminating
}
}
try { Read-OpsJson ./data/servers.csv } catch { "caller saw: $($_.FullyQualifiedErrorId)" }
Passing $_ keeps the original id and exception; the caller sees the error as coming from Read-OpsJson. Actual on 7.6.10: caller saw: System.ArgumentException,Read-OpsJson.
$ok = Get-Item ./data/servers.csv, ./data/nope1, ./data/nope2 -ErrorAction SilentlyContinue -ErrorVariable ev
"{0} ok, {1} failed: {2}" -f @($ok).Count, $ev.Count, (($ev.TargetObject | Split-Path -Leaf) -join ', ')Remove-Item Function:Read-Config, Function:Read-OpsJson -ErrorAction IgnoreCase 1: the “catch-all” that hid a permissions problem
Problem: A provisioning script wrapped everything in try { … } catch { Write-Host 'retrying later' }. For a week it “retried later” forever. Root cause: the catch handled UnauthorizedAccessException (a permanent error) the same way as a transient network blip. Fix: typed catches — transient types (IOException, TimeoutException, HttpRequestException) go to the retry path (Module 7); everything else is logged and rethrown with throw.
Case 2: cleanup that never happened
Problem: A script mounted a share with New-PSDrive, did its work and removed the drive at the end. After failures, stale drives accumulated. Root cause: the removal line was after the work, so any terminating error skipped it. Fix: move cleanup to finally: try { New-PSDrive …; work } finally { Remove-PSDrive X -ErrorAction Ignore }.
Case 3: a module function that “sometimes” stopped the pipeline
Problem: Callers of an internal Get-Tenant function reported that one missing tenant killed their whole report. Root cause: the function used throw for “not found”. Fix: per-item problems use Write-Error (with a proper id via $PSCmdlet.WriteError()), whole-command failures use ThrowTerminatingError; callers who want to stop add -ErrorAction Stop.
Common errors and fixes
Unable to find type [ItemNotFoundException]
Cause: catch types need the full name unless the namespace is loaded with using namespace.
catch [System.Management.Automation.ItemNotFoundException] { }
# or at the top of the script:
using namespace System.Management.AutomationMy typed catch is never hit, the bare catch is
Cause: the actual exception type differs (often a wrapper: MethodInvocationException around an IOException).
catch { $_.Exception.GetType().FullName; $_.Exception.InnerException.GetType().FullName }
Fix: catch the wrapper, or inspect InnerException in a bare catch (OpsKit's Invoke-OpsRetry walks the chain).
The script stops at a harmless Get-Command check after I set Stop
Fix: opt out locally: Get-Command az -ErrorAction Ignore. A global Stop with local exceptions is the right default.
finally printed text into my function's return value
Fix: do not emit output from finally; use Write-Verbose there.
1. Read ./data/opskit.config.psd1; on a missing file print “no config”, on any other error rethrow.
try { Import-PowerShellDataFile -LiteralPath ./data/opskit.config.psd1 -ErrorAction Stop }
catch [System.Management.Automation.ItemNotFoundException] { 'no config' }
catch { throw }2. Run Get-Item on three paths and print only the names of the ones that failed.
$null = Get-Item ./data/a, ./data/servers.csv, ./data/b -ErrorAction SilentlyContinue -ErrorVariable bad $bad.TargetObject | Split-Path -Leaf
Your team's module function Set-OpsDns fails when the DNS server is unreachable. Today it uses throw. A caller runs it for 40 records in a foreach and complains that one bad record aborts the remaining 39. Another caller wants the whole run to stop on the first failure. How do you satisfy both?
Treat an unreachable server for one record as a per-item failure: report it with $PSCmdlet.WriteError() (non-terminating, stable id, TargetObject = the record) and continue. The first caller gets 39 successes and one error in -ErrorVariable. The second caller adds -ErrorAction Stop (or sets the preference), which promotes the first error to script-terminating. If the server is unreachable for all records (detected once in begin), use ThrowTerminatingError. Reserve throw for internal bugs.
Verified teaching videos
Official documentation
- about_Try_Catch_Finally · about_Throw · about_Trap
- about_CommonParameters (-ErrorAction, -ErrorVariable)
Video storyboard (about 90 seconds)
Visual: a try box with Get-Item inside; red text flies past the catch box, which stays dark.
Narration: try only sees terminating errors.
Visual: “-ErrorAction Stop” clicks onto the command; now the error drops into catch.
Narration: promote it at the source, and catch receives the original error.
Visual: three catch boxes stacked; errors fall through until one matches; a finally bar glows at the bottom on every path.
Narration: specific types first, a bare catch last, cleanup in finally.
Visual: three function icons labelled Write-Error, ThrowTerminatingError, throw, with green, yellow and red “caller continues?” lights.
Narration: choose how loudly your function fails.
Module 3 · Native commands: $LASTEXITCODE and $PSNativeCommandUseErrorActionPreference
- Read
$LASTEXITCODEand$?after a native program and know that a non-zero exit is not an error by default (no$Errorentry, no catch). - Turn exit codes into catchable errors with
$PSNativeCommandUseErrorActionPreference = $true+$ErrorActionPreference = 'Stop', and read the resultingNativeCommandExitException. - Handle stderr correctly in 7.x: it is not a failure signal; with
2>&1its lines arrive asErrorRecordobjects. - Handle programs whose non-zero codes mean success (robocopy 1–7) by scoping the preference off.
What: two signals from a native program
| Signal | Where it goes in PowerShell | Means failure? |
|---|---|---|
| Exit code | $LASTEXITCODE (integer); $? becomes $false if non-zero | By convention yes (0 = success) — but some tools differ (robocopy, diff, grep with no match = 1) |
| stdout | Success stream, one [string] per line | No |
| stderr | Straight to the console; with 2>&1 or 2> redirection, one ErrorRecord per line (category NotSpecified, id NativeCommandError) | No. Many tools write progress to stderr (git, curl, terraform). Since 7.2, stderr never sets $? to false and is not affected by $ErrorActionPreference |
Why: the default is “record and continue”
Out of the box, cmd /c exit 3 or a failing git push sets $LASTEXITCODE and $?, writes nothing to $Error, and the next line runs — even inside try with $ErrorActionPreference = 'Stop'. That is exactly Bash without set -e. You must either check $LASTEXITCODE after every call or opt in to the 7.4+ behaviour:
$ErrorActionPreference = 'Stop' $PSNativeCommandUseErrorActionPreference = $true # 7.4+: non-zero exit → NativeCommandExitException
With the preference on, a non-zero exit code produces an error whose severity follows $ErrorActionPreference (Stop → script-terminating; Continue → a displayed non-terminating error). It is the closest thing PowerShell has to set -e, and it does not look at stderr.
How: three patterns
| Pattern | Code | Use when |
|---|---|---|
| Explicit check | git fetch; if ($LASTEXITCODE -ne 0) { throw "git fetch failed: $LASTEXITCODE" } | Works in 5.1 too; you want custom messages per command |
| Global opt-in | $ErrorActionPreference = 'Stop'; $PSNativeCommandUseErrorActionPreference = $true | CI scripts, wrappers around many native calls |
| Scoped opt-out | & { $PSNativeCommandUseErrorActionPreference = $false; robocopy … }; if ($LASTEXITCODE -ge 8) { throw … } | Tools with non-standard exit codes |
When: what to check after which call
$LASTEXITCODEis set only by native programs and by scripts that callexit; cmdlets do not touch it. Read it immediately — the next native call overwrites it.$?after a native call is$falseexactly when the exit code is non-zero (7.2+).- Redirecting stderr:
2>$nulldiscards it;2>&1merges it as ErrorRecords (convert with| ForEach-Object { "$_" }if you want plain strings). In 7.x, those redirected records are not added to$Error(verified). - Bash comparison:
set -e≈$PSNativeCommandUseErrorActionPreference = $true+ Stop;set -o pipefail— PowerShell pipelines of native commands report the last command's exit code; check each step if it matters.
$PSNativeCommandUseErrorActionPreference is on by default in 7.4+” — it is a mainstream feature but defaults to $false (verified). ④ “Every non-zero exit is a failure” — robocopy returns 1 when it copied files. ⑤ “$LASTEXITCODE tells me whether my last cmdlet worked” — cmdlets never set it.Diagram: from exit code to PowerShell error
Native exit code router
Pick a native call and the preference settings; follow the exit code and stderr through PowerShell.
$global:LASTEXITCODE and sets $?. If $PSNativeCommandUseErrorActionPreference is $true and the code is non-zero, the engine writes an ErrorRecord wrapping System.Management.Automation.NativeCommandExitException (with ExitCode, Path, ProcessId) through the normal error pipeline, so $ErrorActionPreference decides its severity. stderr is read asynchronously and only becomes ErrorRecords when redirected.Command table
| Item | Purpose | Notes |
|---|---|---|
$LASTEXITCODE | Last native exit code | Global; overwritten by the next native call or exit |
$? | Success of last statement | For natives: exit code = 0 |
$PSNativeCommandUseErrorActionPreference | Exit code → error | 7.4+; default $false; scope it like any variable |
2>$null | Discard stderr | Does not change the exit code |
2>&1 | Merge stderr into output | Lines become ErrorRecords; "$_" gives the text |
[System.Management.Automation.NativeCommandExitException] | Catch type | .ExitCode, .Path |
Start-Process -Wait -PassThru | Run without capturing output | .ExitCode on the returned process; rarely needed |
cmd /c exit 3; "LASTEXITCODE=$LASTEXITCODE ?=$?" # Linux/macOS: sh -c 'exit 3'
cmd /c exit 0; "LASTEXITCODE=$LASTEXITCODE ?=$?"
try { cmd /c exit 3; 'try finished: native failure is not an exception' } catch { 'caught' }
LASTEXITCODE=3 ?=False LASTEXITCODE=0 ?=True try finished: native failure is not an exception
How to verify: $Error.Count does not change after a failing native call. Common mistake: wrapping terraform apply in try/catch and assuming failures are caught. Production use: CI scripts start with the two preference lines; wrappers that must tolerate some codes scope the preference off.
Opt in: non-zero exit becomes an exception
$PSNativeCommandUseErrorActionPreference # default
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
try { cmd /c exit 3; 'not reached' }
catch {
$_.Exception.GetType().FullName
$_.Exception.Message
"ExitCode property: $($_.Exception.ExitCode)"
$_.FullyQualifiedErrorId
}
False System.Management.Automation.NativeCommandExitException Program "cmd.exe" ended with non-zero exit code: 3 (0x00000003). ExitCode property: 3 ProgramExitedWithNonZeroCode
# Same preference, but $ErrorActionPreference left at Continue: shown, not fatal $PSNativeCommandUseErrorActionPreference = $true cmd /c exit 3; "Continue preference: LASTEXITCODE=$LASTEXITCODE"
NativeCommandExitException: Program "cmd.exe" ended with non-zero exit code: 3 (0x00000003). Continue preference: LASTEXITCODE=3
stderr is not failure
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
cmd /c "echo to-stderr 1>&2"; "stderr alone did not stop anything, exit=$LASTEXITCODE"
$out = cmd /c "echo line1 & echo oops 1>&2 & echo line2" 2>&1
$out | ForEach-Object { '{0,-12} {1}' -f $_.GetType().Name, $_ }
to-stderr stderr alone did not stop anything, exit=0 String line1 ErrorRecord oops String line2
cmd /c "echo oops 1>&2" 2>$null; "?=$? LASTEXITCODE=$LASTEXITCODE" $r = cmd /c "echo out & echo err 1>&2" 2>&1; $r.Count; $Error.Count
?=True LASTEXITCODE=0 2 0
git: exit codes and stderr records
git --no-such-option 2>$null; "git exit=$LASTEXITCODE"
git -C ./data rev-parse --is-inside-work-tree 2>&1 | ForEach-Object { "[{0}] {1}" -f $_.GetType().Name, $_ }; "git exit=$LASTEXITCODE"
git exit=129 [ErrorRecord] fatal: not a git repository (or any of the parent directories): .git git exit=128
The robocopy trap and the scoped opt-out
$PSNativeCommandUseErrorActionPreference = $true $ErrorActionPreference = 'Stop' robocopy ./data/files ./tmp/files-copy /E /NJH /NJS /NP /NFL /NDL; "robocopy exit=$LASTEXITCODE"
NativeCommandExitException: Program "Robocopy.exe" ended with non-zero exit code: 1 (0x00000001).
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
& { $PSNativeCommandUseErrorActionPreference = $false; robocopy ./data/files ./tmp/files-copy2 /E /NJH /NJS /NP /NFL /NDL }
if ($LASTEXITCODE -ge 8) { throw "robocopy failed: $LASTEXITCODE" }
"robocopy exit=$LASTEXITCODE (0-7 = success for robocopy)"
robocopy exit=1 (0-7 = success for robocopy)
The child scope & { } turns the preference off only for that block; $LASTEXITCODE is global, so the check after the block still sees robocopy's code. On Linux the same applies to grep (1 = no match) and diff (1 = files differ).
Goal: Build a small wrapper that runs native tools safely. Environment: ~/pslab; Windows examples use cmd/robocopy, Linux/macOS use sh/rsync. Cost: none; copies stay in ~/pslab/tmp.
$Error stays empty.pwsh -NoProfile, set both preferences and run git --no-such-option inside try; print $_.Exception.ExitCode (expected: 129).function Invoke-Native {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$FilePath, [string[]]$ArgumentList = @(), [int[]]$SuccessCodes = 0)
$out = & $FilePath @ArgumentList 2>&1 | ForEach-Object { "$_" }
$code = $LASTEXITCODE
if ($code -notin $SuccessCodes) {
$PSCmdlet.ThrowTerminatingError([System.Management.Automation.ErrorRecord]::new(
[System.Exception]::new("$FilePath exited with $code`n$($out -join "`n")"),
'Native.ExitCode', 'NotSpecified', $FilePath))
}
$out
}
Invoke-Native git '--version'
try { Invoke-Native git '--no-such-option' } catch { $_.FullyQualifiedErrorId }
Invoke-Native robocopy './data/files', './tmp/rc', '/E', '/NJH', '/NJS', '/NP', '/NFL', '/NDL' -SuccessCodes (0..7) # Windows
The helper keeps stdout and stderr together as plain text, defines success per tool, and raises one error with a stable id and the tool's output in the message. Actual run on 7.6.10: the first line printed git version 2.51.2.windows.1, the second Native.ExitCode,Invoke-Native, and the robocopy line produced no output and no error.
Remove-Item ./tmp/files-copy, ./tmp/files-copy2, ./tmp/rc -Recurse -Force -ErrorAction IgnoreCase 1: a green pipeline that deployed nothing
Problem: A GitHub Actions step ran az deployment group create … followed by Write-Host 'Deployed'. The deployment failed validation; the step was green. Root cause: az exited with 1, but the step script's last command (Write-Host) succeeded, so the step exited 0. Fix: start every pwsh CI script with $ErrorActionPreference = 'Stop' and $PSNativeCommandUseErrorActionPreference = $true (or check $LASTEXITCODE after each native call).
Case 2: Windows PowerShell 5.1 stopping on git progress
Problem: An old 5.1 build script with $ErrorActionPreference = 'Stop' died on git clone … 2>&1 although the clone succeeded. Root cause: in 5.1, redirected stderr lines were real errors subject to the preference; git writes progress to stderr. Fix: move to pwsh 7.2+ (stderr no longer triggers Stop), or in 5.1 run git without 2>&1 and check $LASTEXITCODE.
Case 3: robocopy “fails” after a team turned on the preference
Problem: After adopting the 7.4 preference globally, every file-sync job failed — exactly when files had been copied. Root cause: robocopy exit codes are a bit field: 1 = files copied, 2 = extra files, 8+ = failure (verified: exit 1 became NativeCommandExitException). Fix: scoped opt-out plus if ($LASTEXITCODE -ge 8), or a helper with -SuccessCodes (0..7).
Common errors and fixes
NativeCommandExitException: Program "X" ended with non-zero exit code
Cause: the preference is on and the tool returned non-zero. Fix: decide whether that code is a failure for this tool; if not, scope the preference off for that call.
$LASTEXITCODE is 0 but the tool clearly failed
Cause: another native call or an exit 0 script ran in between, or the tool really returns 0 on failure (some vendor CLIs). Fix: capture $code = $LASTEXITCODE immediately; for odd tools parse their output.
Red text from git/curl in my logs makes people think the job failed
Fix: use the tool's quiet flag (git -q, curl -sS) or capture stderr with 2>&1 and log it as information; judge success by exit code.
The variable $PSNativeCommandUseErrorActionPreference does nothing
$PSVersionTable.PSVersion; $ErrorActionPreference
Cause: version below 7.3 (experimental only) or 5.1; or $ErrorActionPreference is SilentlyContinue. Fix: pwsh 7.4+ and Stop.
1. Run git status in ~/pslab/data and print “not a repo” if it fails, without any red text.
git -C ~/pslab/data status 2>$null | Out-Null
if ($LASTEXITCODE -ne 0) { 'not a repo' }2. Make a script fail with the native tool's exit code (for a scheduler).
git fetch
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }A release script runs terraform plan -detailed-exitcode, which returns 0 (no changes), 1 (error) or 2 (changes present). The team turned on $PSNativeCommandUseErrorActionPreference and now the script dies whenever there are changes. Design the fix.
Exit code 2 is a result, not an error. Run that one command with the preference off in a child scope, capture $code = $LASTEXITCODE, then switch ($code) { 0 { 'no changes' } 2 { 'changes: continue to apply' } default { throw "terraform plan failed: $code" } }. Keep the preference on for every other native call, so unexpected failures still stop the run.
Verified teaching videos
No verified video was found that covers $PSNativeCommandUseErrorActionPreference or 7.x stderr behaviour specifically. The general error-handling videos below mention $LASTEXITCODE; this module and the documentation are authoritative.
Official documentation
- about_Preference_Variables ($PSNativeCommandUseErrorActionPreference) · What's New in PowerShell 7.4
- about_Automatic_Variables ($LASTEXITCODE) · about_Redirection
Video storyboard (about 90 seconds)
Visual: a git process box with three pipes — stdout, stderr, exit code — flowing into PowerShell.
Narration: a native program speaks in text and one number.
Visual: exit code 3 lands in $LASTEXITCODE; a try/catch box stays dark; the next line runs.
Narration: by default PowerShell writes it down and moves on.
Visual: two switches flip (Stop, UseErrorActionPreference); exit code 3 becomes a red exception that drops into catch.
Narration: opt in, and a non-zero exit becomes a real error.
Visual: robocopy shows “1 = files copied” and a small child-scope box switching the preference off.
Narration: know your tool's codes, and scope the exception.
Module 4 · The six streams, redirection and preference variables
- Name the six streams, their
Write-*cmdlets, preference variables and record types. - Redirect with
n>,n>>,n>&1,*>and>$null; capture each stream separately with-ErrorVariable,-WarningVariable,-InformationVariable. - Explain why
Write-Hostoutput is not captured by$r = …but is captured by6>&1(5.0+). - Use
-Verbose/-Debugso that diagnostics flow into nested advanced functions.
What: the streams
| # | Stream | Write with | Preference (default) | Common parameter | Record type |
|---|---|---|---|---|---|
| 1 | Success (output) | bare value, Write-Output | — | -OutVariable | the object itself |
| 2 | Error | Write-Error | $ErrorActionPreference (Continue) | -ErrorAction, -ErrorVariable | ErrorRecord |
| 3 | Warning | Write-Warning | $WarningPreference (Continue) | -WarningAction, -WarningVariable | WarningRecord |
| 4 | Verbose | Write-Verbose | $VerbosePreference (SilentlyContinue) | -Verbose | VerboseRecord |
| 5 | Debug | Write-Debug | $DebugPreference (SilentlyContinue) | -Debug | DebugRecord |
| 6 | Information | Write-Information, Write-Host | $InformationPreference (SilentlyContinue) | -InformationAction, -InformationVariable | InformationRecord (Write-Host adds tag PSHOST) |
| — | Progress | Write-Progress | $ProgressPreference (Continue) | — | not redirectable |
Why: data and diagnostics must not mix
In Bash a function returns data on stdout and must send every log line to stderr (>&2), or the caller's $(…) captures garbage. PowerShell gives you five non-data channels, each with a switch. Rule: only data goes to stream 1; progress messages go to Verbose or Information; problems go to Warning or Error. Then $servers = Get-OpsServer captures servers and nothing else.
How: redirection operators
| Operator | Effect | Example |
|---|---|---|
> file, >> file | Stream 1 to a file (overwrite / append) | Get-OpsServer > ./tmp/s.txt |
n> file | Stream n to a file | 2> ./tmp/err.txt, 3> ./tmp/warn.txt |
n>&1 | Merge stream n into success | $all = f 2>&1 |
*>, *>&1 | All streams | f *> ./tmp/all.txt |
n>$null | Discard stream n | 6>$null hides Write-Host |
Redirection to a file uses Out-File encoding (UTF-8 without BOM in 7.x) and formats objects like the console would — it is not structured logging (Module 7).
When: Verbose vs Information vs Host
- Write-Verbose: “what am I doing” details for troubleshooting; off unless the caller asks with
-Verbose. In an advanced function,-Verbosesets$VerbosePreferencelocally, so nested advanced functions inherit it (verified below). - Write-Information: messages an operator might want, off by default; turn on with
-InformationAction Continue; collect with-InformationVariableincluding tags. - Write-Host: user-facing display for interactive tools. Since PowerShell 5.0 it writes an InformationRecord to stream 6 and is displayed regardless of
$InformationPreference. It is not captured by assignment, but6>&1or-InformationVariablecapture it. - Write-Warning: something is wrong but the command continues (e.g. “backup already exists”).
Write-Output is needed to return data” — a bare value does the same. ③ “*> captures verbose output” — only if the stream is enabled; verbose and debug records that are switched off are never created (verified: *> file had no verbose/debug lines). ④ “Redirection makes structured logs” — it writes formatted text. ⑤ “-Verbose on my function also shows verbose output of cmdlets inside” — yes for advanced functions and cmdlets in the same call chain; plain (non-advanced) functions have no -Verbose parameter.Diagram: one function, six exits
Stream router
Choose a message and a caller setting; see which stream it takes, whether a preference lets it through, where redirection sends it, and what the caller ends up with.
Write-* cmdlet calls a WriteXxx() method on the command runtime. The runtime checks the effective preference (common parameter first, then the preference variable in scope) — for Verbose and Debug with SilentlyContinue the record is dropped; then it appends to any -XxxVariable list, applies redirection (merging into the output pipe or sending to a file) and finally hands the rest to the host, which colours and prefixes them (WARNING:, VERBOSE:).Command table
| Command | Purpose | Notes |
|---|---|---|
Write-Verbose 'x' | Diagnostic detail | Shown with -Verbose |
Write-Information 'x' -Tags a,b | Operator messages | -InformationAction Continue to show |
Write-Warning 'x' | Non-fatal problem | Prefix WARNING: |
Write-Debug 'x' | Developer detail | 7.x: -Debug no longer prompts (it sets Continue) |
Get-Variable *Preference | Show all preferences | See below |
f 2>&1 | Group-Object { $_.GetType().Name } | Split merged streams | By record type |
function Write-AllStreams {
[CmdletBinding()] param()
'success (1)'
Write-Error 'error (2)'
Write-Warning 'warning (3)'
Write-Verbose 'verbose (4)'
Write-Debug 'debug (5)'
Write-Information 'information (6)'
Write-Host 'host -> information (6)'
}
Write-AllStreams
success (1) Write-AllStreams: error (2) WARNING: warning (3) host -> information (6)
How to verify: verbose, debug and Write-Information are hidden by default; Write-Host is not. Common mistake: using Write-Host for progress inside functions that are used in pipelines — it cannot be turned off without 6>$null. Production use: Verbose for details, Information for operator messages, Warning for anomalies.
Merge everything and look at the record types
$all = Write-AllStreams -Verbose -Debug -InformationAction Continue *>&1
$all | ForEach-Object { '{0,-18} {1}' -f $_.GetType().Name, $_ }
String success (1) ErrorRecord error (2) WarningRecord warning (3) VerboseRecord verbose (4) DebugRecord debug (5) InformationRecord information (6) InformationRecord host -> information (6)
Capture each stream separately
$data = Write-AllStreams -ErrorVariable errs -WarningVariable warns -InformationVariable infos 2>$null 3>$null 6>$null
"data: $data"
"errs: $($errs.Count) warns: $($warns.Count) infos: $($infos.Count)"
$infos | ForEach-Object { "{0} tags={1}" -f $_.MessageData, ($_.Tags -join ',') }
data: success (1) errs: 1 warns: 1 infos: 2 information (6) tags= host -> information (6) tags=PSHOST
-InformationVariable collected the Write-Information record although $InformationPreference was SilentlyContinue; the PSHOST tag identifies Write-Host.
Write-Host and assignment
function Get-Report { 'report-data'; Write-Host 'Working...' }
$r = Get-Report
"captured: $r"
$r2 = Get-Report 6>&1
"captured with 6>&1: $($r2 -join ' | ')"
Get-Report 6>$null
Working... captured: report-data captured with 6>&1: report-data | Working... report-data
Streams to files
Write-AllStreams 2> ./tmp/err.txt 3> ./tmp/warn.txt > ./tmp/out.txt Get-Content ./tmp/out.txt, ./tmp/err.txt, ./tmp/warn.txt '---' Write-AllStreams *> ./tmp/all.txt; Get-Content ./tmp/all.txt
host -> information (6) success (1) Write-AllStreams: error (2) warning (3) --- success (1) Write-AllStreams: error (2) warning (3) information (6) host -> information (6)
Two observations from the real run: in the first command Write-Host still reached the console (stream 6 was not redirected); in the second, *> wrote the Write-Information line to the file even though it is hidden on the console by default — but no verbose or debug lines, because those records are never created while their preference is SilentlyContinue.
Preference variables and nested -Verbose
Get-Variable *Preference | Sort-Object Name | Format-Table Name, Value -AutoSize
function Inner { [CmdletBinding()] param() Write-Verbose 'inner verbose' }
function Outer { [CmdletBinding()] param() Write-Verbose 'outer verbose'; Inner }
Outer -Verbose
Name Value ---- ----- ConfirmPreference High DebugPreference SilentlyContinue ErrorActionPreference Continue InformationPreference SilentlyContinue ProgressPreference Continue PSNativeCommandUseErrorActionPreference False VerbosePreference SilentlyContinue WarningPreference Continue WhatIfPreference False VERBOSE: outer verbose VERBOSE: inner verbose
Goal: Give an OpsKit-style function clean streams and capture each one from a caller. Environment: ~/pslab. Cost: files in ~/pslab/tmp.
function Get-ProdServer {
[CmdletBinding()] param()
Write-Verbose 'reading ./data/servers.csv'
$rows = Import-Csv ./data/servers.csv
Write-Information "loaded $($rows.Count) rows" -Tags 'inventory'
$prod = $rows | Where-Object Env -eq 'prod'
if (@($prod | Where-Object Monitored -eq 'false').Count) { Write-Warning 'some prod servers are not monitored' }
$prod
}
$s = Get-ProdServer -InformationVariable info -WarningVariable warn 3>$null
"servers=$(@($s).Count) info='$($info.MessageData)' warning='$warn'"
Actual output (7.6.10): servers=6 info='loaded 12 rows' warning='some prod servers are not monitored' — db-01 and bastion-01 in prod have Monitored = false.
Get-ProdServer -Verbose | Out-Null shows the VERBOSE line; nothing else changes.>out 2>err): Get-ProdServer > ./tmp/prod.txt 3> ./tmp/prod.warn.txt, then read both files.Remove-Item ./tmp/*.txtCase 1: a function that returned “Connecting…” as data
Problem: $ip = Get-VmIp vm01 sometimes produced Connecting... 10.0.0.4 and broke the next command. Root cause: the function used Write-Output 'Connecting...' (stream 1) for a progress message. Fix: Write-Verbose for progress; only the IP goes to stream 1. In Bash terms: logs to stderr, data to stdout.
Case 2: a scheduled job with no diagnostics
Problem: When a nightly job failed, the log had only the final error. Root cause: details were written with Write-Verbose, which is off by default. Fix: run the scheduled job with -Verbose and *>> job.log, or better, write structured events with OpsKit's JSON-lines log (Module 7) and keep verbose for humans.
Case 3: “Write-Host output vanished in the container”
Problem: An engineer captured a script's output with $o = ./report.ps1 6>&1 and suddenly saw extra lines in the data. Root cause: merging stream 6 brought Write-Host records into the variable. Fix: filter by type ($o | Where-Object { $_ -isnot [System.Management.Automation.InformationRecord] }) or capture information separately with -InformationVariable.
Common errors and fixes
-Verbose does nothing for my function
Cause: the function is not advanced (no [CmdletBinding()] or [Parameter()]), so -Verbose is not even a parameter — or it is passed positionally to something else.
(Get-Command MyFunc).CmdletBinding
My variable contains ErrorRecords mixed with data
Cause: 2>&1 or *>&1. Fix: split by type, or use -ErrorVariable instead of merging.
Write-Information messages never appear
Fix: -InformationAction Continue on the call, or $InformationPreference = 'Continue' in the script.
A progress bar slows down my file download loop
Fix: $ProgressPreference = 'SilentlyContinue' in non-interactive scripts (progress is not a redirectable stream).
1. Run Write-AllStreams and keep only the warnings, as strings.
Write-AllStreams 3>&1 2>$null 6>$null | Where-Object { $_ -is [System.Management.Automation.WarningRecord] } | ForEach-Object Message2. Silence a chatty script's Write-Host lines but keep its data.
$data = ./chatty.ps1 6>$null
A shared module prints colourful progress with Write-Host in every function. The automation team wants silent runs with a machine-readable record of what happened; the helpdesk wants the colourful text. How do you serve both without forking the module?
Replace Write-Host progress with Write-Information (with tags) and Write-Verbose. Interactive users run with $InformationPreference = 'Continue' in their profile (or the module offers a -Show switch); automation runs silently and collects -InformationVariable, which keeps tags and timestamps (TimeGenerated) for structured logs. If Write-Host must stay for colours, automation can still drop it with 6>$null or capture it via -InformationVariable because it is stream 6.
Verified teaching videos
No verified video was found that is specifically about the six streams and redirection in PowerShell 7. The documentation below is the reference; John Savill's master class touches output and the pipeline:
Official documentation
Video storyboard (about 90 seconds)
Visual: a function with six coloured pipes; only the green one (1) feeds a variable.
Narration: data on stream one; everything else has its own lane.
Visual: valves labelled Preference close the verbose and debug pipes; -Verbose opens one.
Narration: preferences decide what is shown; common parameters override them.
Visual: 2>&1 bends the red pipe into the green; 3> file diverts yellow into a document.
Narration: redirection merges or diverts any stream.
Visual: Write-Host labelled “stream 6” with a PSHOST tag.
Narration: Write-Host is information with a guaranteed display. Fine for people, wrong for data.
Module 5 · Strict mode and defensive coding
- Reproduce four silent bugs (typo'd variable, typo'd property or hashtable key, method-call syntax for a function, index past the end) and catch each with
Set-StrictMode -Version Latest. - Know strict mode's scope rules: it applies to the current scope and its children, and a module has its own setting.
- Write guard clauses and validation attributes (
ValidateRange,ValidateSet,ValidateScriptwithErrorMessage), and compare with$nullon the left. - Put
-ErrorAction Stop/$ErrorActionPreference = 'Stop'at the boundaries (script entry, module scope) rather than everywhere.
What: what each strict-mode version checks
| Check | Off (default) | -Version 1.0 | 2.0 | 3.0 / Latest |
|---|---|---|---|---|
Reading an uninitialized variable ($destinaton) | $null | error (except inside strings) | error | error |
Reading a property that does not exist ($o.Nmae) | $null | — | error | error — also for missing hashtable keys via dot notation (verified) |
Calling a function like a method f(1,2) | passes one array | — | error | error |
Variable without a name ${} | allowed | — | error | error |
Index out of bounds $a[5] | $null | — | — | error |
Latest means the highest version this PowerShell knows (3.0 on 7.6). Bash equivalent: set -u covers only the first row.
Why: typos are the cheapest bugs to prevent
Without strict mode, Remove-Item "$backupDir/$fileName" with a misspelled $fileNmae becomes Remove-Item "$backupDir/". That is not hypothetical — it is the classic rm -rf "$DIR/" accident in every shell. Strict mode turns the read of an unset variable into an error before the dangerous command runs. OpsKit v0.3 sets Set-StrictMode -Version Latest at the top of OpsKit.psm1, which covers every function in the module and no caller code.
How: defensive patterns
| Pattern | Example | What it prevents |
|---|---|---|
| Guard clause (fail fast) | if (-not (Test-Path -LiteralPath $Source -PathType Container)) { $PSCmdlet.ThrowTerminatingError(…) } | Working on the wrong or missing input; deep nesting |
| Validation attributes | [ValidateRange(1,365)][int]$Keep, [ValidateSet('dev','staging','prod')], [ValidateScript({…}, ErrorMessage = '…')] | Bad values never reach your code; error appears at binding time with a clear message |
$null on the left | if ($null -eq $result) | $array -eq $null filters the array instead of testing it |
| Force arrays | @($servers).Count | A single object or $null having no reliable .Count semantics in older code |
ContainsKey / index syntax for optional keys | if ($cfg.ContainsKey('Backup')), $h['Kepe'] | Strict-mode errors for optional settings (index syntax returns $null) |
| Stop at the boundary | Top of script / psm1: $ErrorActionPreference = 'Stop'; local opt-outs with -ErrorAction Ignore | Continuing after a failed step |
When: scope rules
Set-StrictModeaffects the scope where it runs and all child scopes; a child can turn it off for itself (Set-StrictMode -Off) without changing the parent (verified below).- Modules have their own session state: strict mode in your script does not apply inside a module, and the module's setting does not leak out.
- Do not put
Set-StrictModein your profile for interactive use if you paste a lot of sample code — but always in scripts and modules.
set -e” — it catches coding mistakes, not failed commands; combine it with $ErrorActionPreference = 'Stop'. ② “Missing hashtable keys are fine under strict mode” — with dot notation they throw under Latest (verified); use ContainsKey or $h['key']. ③ “$x -eq $null and $null -eq $x are the same” — not when $x is an array. ④ “Validation is just documentation” — it runs at binding time and produces errors before your function body runs. ⑤ “Strict mode in my script protects the modules I call” — each module decides for itself.Diagram: layers of defence for one parameter
Strict-mode checker
Pick a buggy line and compare what happens with strict mode off and with -Version Latest. All outputs were reproduced on 7.6.10.
RuntimeException (for example VariableIsUndefined or PropertyNotFoundStrict) instead of returning $null. The method-call check happens when a command is invoked with parenthesised, comma-separated arguments.Command table
| Command | Purpose | Notes |
|---|---|---|
Set-StrictMode -Version Latest | Enable all checks | Top of every script and .psm1 |
Set-StrictMode -Off | Disable in this scope | For a block of legacy code |
[ValidateRange(1, 30)] | Numeric range | Also Positive, NonNegative |
[ValidateSet('a','b')] | Allowed values + tab completion | Case-insensitive |
[ValidateScript({ … }, ErrorMessage = '… {0}')] | Custom check with a readable message | {0} is the value |
[ValidateNotNullOrEmpty()] | Reject '' / $null | Also ValidateNotNullOrWhiteSpace (7.4+) |
$null -eq $x | Null test | $null always on the left |
Four silent bugs with strict mode off
$cfg = Import-PowerShellDataFile ./data/opskit.config.psd1
"keep=[$($cfg.Backup.Kepe)] dest=[$destinaton]"
function Add-Numbers($a, $b) { $a + $b }
Add-Numbers(1, 2)
$list = 1, 2, 3; "fourth=[$($list[3])]"
keep=[] dest=[] 1 2 fourth=[]
No error at all. Add-Numbers(1, 2) passed the array 1,2 as $a and nothing as $b, so it returned the array.
The same bugs with strict mode Latest (each run in a fresh session)
Set-StrictMode -Version Latest $cfg = Import-PowerShellDataFile ./data/opskit.config.psd1 "dest=[$destinaton]"
InvalidOperation: The variable '$destinaton' cannot be retrieved because it has not been set.
Set-StrictMode -Version Latest
$o = [pscustomobject]@{ Name = 'web-01' }
$o.Nmae
PropertyNotFoundException: The property 'Nmae' cannot be found on this object. Verify that the property exists.
Set-StrictMode -Version Latest $cfg = Import-PowerShellDataFile ./data/opskit.config.psd1 "hashtable key: [$($cfg.Backup.Kepe)]"
PropertyNotFoundException: The property 'Kepe' cannot be found on this object. Verify that the property exists. hashtable key: []
Inside a string the failing subexpression is reported and evaluates to nothing — the string itself is still produced. On a line of its own ($cfg.Backup.Kepe) the statement stops.
Set-StrictMode -Version Latest
function Add-Numbers($a, $b) { $a + $b }
Add-Numbers(1, 2)
InvalidOperation: The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic.
Set-StrictMode -Version Latest $list = 1, 2, 3 $list[3]
OperationStopped: Index was outside the bounds of the array.
Scope: a child can switch it off, the parent keeps it
Set-StrictMode -Version Latest
function Get-Inner { $undefinedInner }
& { Set-StrictMode -Off; "child scope off: [$undefinedChild]" }
"script scope still Latest:"
Get-Inner
child scope off: [] script scope still Latest: InvalidOperation: The variable '$undefinedInner' cannot be retrieved because it has not been set.
$null on the left
$servers = Import-Csv ./data/servers.csv $none = $servers | Where-Object Env -eq 'qa' "none -eq null: " + ($none -eq $null) $arr = @($null, 1, $null) "arr -eq null returns: " + ($arr -eq $null).Count + " items -> if() sees " + [bool]($arr -eq $null) "null -eq arr: " + ($null -eq $arr) "count of none: " + @($none).Count
none -eq null: True arr -eq null returns: 2 items -> if() sees True null -eq arr: False count of none: 0
With an array on the left, -eq is a filter: it returned the two $null elements, and a 2-element array is truthy. $null -eq $arr asks the real question.
Validation attributes
function Set-OpsKeep {
[CmdletBinding()]
param(
[Parameter(Mandatory)][ValidateRange(1, 30)][int]$Keep,
[ValidateSet('dev', 'staging', 'prod')][string]$Environment = 'dev',
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Container }, ErrorMessage = 'Folder not found: {0}')]
[string]$Destination = '.'
)
"ok: keep $Keep in $Environment at $Destination"
}
Set-OpsKeep -Keep 7
Set-OpsKeep -Keep 0
Set-OpsKeep -Keep 7 -Environment qa
Set-OpsKeep -Keep 7 -Destination ./nope
ok: keep 7 in dev at . Set-OpsKeep: Cannot validate argument on parameter 'Keep'. The 0 argument is less than the minimum allowed range of 1. Supply an argument that is greater than or equal to 1 and then try the command again. Set-OpsKeep: Cannot validate argument on parameter 'Environment'. The argument "qa" does not belong to the set "dev,staging,prod" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again. Set-OpsKeep: Cannot validate argument on parameter 'Destination'. Folder not found: ./nope
How to verify: validation errors are parameter-binding errors (statement-terminating, ParameterArgumentValidationError), raised before any line of the body runs. Common mistake: validating inside the body with ifs after side effects already happened. Production use: every OpsKit parameter that controls deletion (-Keep) has a range.
Goal: Find bugs in a small script by turning strict mode on. Environment: ~/pslab. Cost: none.
~/pslab/scripts/Get-BackupPlan.ps1 (it contains three deliberate bugs):
param([int]$Keep = 7) $cfg = Import-PowerShellDataFile (Join-Path $PSScriptRoot '..' 'data' 'opskit.config.psd1') $dest = $cfg.Backup.Destinaton # bug 1: typo in key $excluded = $cfg.Backup.Exclude "Plan: keep $Keep archives in [$dest], skip $($exlcuded -join ', ')" # bug 2: typo in variable $first = @(Get-ChildItem (Join-Path $PSScriptRoot '..' 'data') -File)[10] # bug 3: only 4 files "First file to back up: $($first.Name)"
./scripts/Get-BackupPlan.ps1
Plan: keep 7 archives in [], skip First file to back up:
Three bugs, zero errors.
Set-StrictMode -Version Latest as the second line (after param) and run it with pwsh -NoProfile -File ./scripts/Get-BackupPlan.ps1:
PropertyNotFoundException: C:\Users\labadmin\pslab\scripts\Get-BackupPlan.ps1:4
Line |
4 | $dest = $cfg.Backup.Destinaton # bug 1: typo in …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The property 'Destinaton' cannot be found on this object. Verify that the property exists.
InvalidOperation: C:\Users\labadmin\pslab\scripts\Get-BackupPlan.ps1:6
Line |
6 | "Plan: keep $Keep archives in [$dest], skip $($exlcuded -join ', ')" …
| ~~~~~
| The variable '$dest' cannot be retrieved because it has not been set.
OperationStopped: C:\Users\labadmin\pslab\scripts\Get-BackupPlan.ps1:7
Line |
7 | $first = @(Get-ChildItem (Join-Path $PSScriptRoot '..' 'data') -File) …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Index was outside the bounds of the array.
InvalidOperation: C:\Users\labadmin\pslab\scripts\Get-BackupPlan.ps1:8
Line |
8 | "First file to back up: $($first.Name)"
| ~~~~~~
| The variable '$first' cannot be retrieved because it has not been set.
First file to back up:
Every strict-mode error is statement-terminating, so the script kept going and produced follow-on errors ($dest and $first were never assigned). The $exlcuded typo is hidden behind the $dest error; it appears after you fix bug 1. Lesson: strict mode finds bugs, but only $ErrorActionPreference = 'Stop' or try/catch makes the script stop at the first one — add both lines.
[ValidateRange(1, 365)] to $Keep, and a guard clause if (-not $cfg.ContainsKey('Backup')) { throw 'config has no Backup section' }.Remove-Item ./scripts/Get-BackupPlan.ps1.Case 1: the empty variable that deleted a share
Problem: A cleanup script ran Remove-Item "$root\$tenantFolder" -Recurse -Force; a refactor renamed $tenantFolder to $tenantDir in one place only. The path became $root\. Root cause: no strict mode, no validation. Fix: Set-StrictMode -Version Latest; a guard clause that refuses to delete anything shorter than two path segments below a known root; SupportsShouldProcess so the change can be previewed (Module 6).
Case 2: if ($result -eq $null) that was never true
Problem: A health check reported “no failed hosts” although several had failed. Root cause: $failed was an array containing $null placeholders; $failed -eq $null returned the null elements (truthy), so the branch logic was inverted. Fix: $null -eq $failed for null checks and @($failed).Count -eq 0 for emptiness. PSScriptAnalyzer rule PSPossibleIncorrectComparisonWithNull flags this (Lesson 8).
Case 3: strict mode broke an old module after an upgrade
Problem: After a team added Set-StrictMode -Version Latest to their own module, a call into a third-party module started failing. Root cause: it did not — strict mode does not cross module boundaries. The real cause was their own code reading an optional config key with dot notation. Fix: $cfg['Optional'] or ContainsKey for optional settings.
Common errors and fixes
The variable '$x' cannot be retrieved because it has not been set
Cause: typo, or a variable only set in one branch. Fix: fix the name, or initialise before the branch ($x = $null).
The property 'X' cannot be found on this object
Cause: typo, an optional property/key, or the object is a different type than you think.
$obj | Get-Member -MemberType Properties
$h.ContainsKey('X'); $h['X']
$obj.PSObject.Properties.Name -contains 'X'The function or command was called as if it were a method
Fix: call commands with spaces: Add-Numbers 1 2 or Add-Numbers -a 1 -b 2.
Cannot validate argument on parameter …
Cause: working as designed. Fix: pass a valid value; read the attribute with (Get-Command f).Parameters['Keep'].Attributes.
1. Read Backup.Keep from the config, defaulting to 7 when the key is missing, safely under strict mode.
Set-StrictMode -Version Latest
$cfg = Import-PowerShellDataFile ./data/opskit.config.psd1
$keep = if ($cfg.ContainsKey('Backup') -and $cfg.Backup.ContainsKey('Keep')) { $cfg.Backup.Keep } else { 7 }2. Write a parameter that accepts only an existing folder and says so in plain words.
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Container }, ErrorMessage = 'Not a folder: {0}')]
[string]$DestinationA reviewer says: “Strict mode and $ErrorActionPreference = 'Stop' at the top of the .psm1 are enough; we don't need validation attributes.” Do you agree?
No. Strict mode catches mistakes in your code; Stop catches failed commands. Neither knows that -Keep 0 would delete every backup — that is a perfectly valid integer. Validation attributes encode business rules at the boundary, fail before any side effect, produce messages that name the parameter, and document the contract in Get-Help. Use all three layers.
Verified teaching videos
No verified video was found that covers Set-StrictMode specifically. Use the documentation; the error-handling guide below covers defensive scripting in general.
Official documentation
- Set-StrictMode · Everything you wanted to know about $null
- about_Functions_Advanced_Parameters (validation attributes)
Video storyboard (about 90 seconds)
Visual:
Remove-Item "$root/$fileNmae"; the variable fades to empty and the path shrinks to $root/.Narration: one typo, and the target is the whole folder.
Visual: Set-StrictMode Latest switches on; the same line now stops with a red “has not been set”.
Narration: strict mode turns silent nulls into errors.
Visual: a parameter with three attribute badges rejecting -Keep 0 at the door.
Narration: validate at binding time, before anything changes.
Visual:
$null -eq $x with $null highlighted on the left.Narration: null on the left, always.
Module 6 · Safe change: SupportsShouldProcess, -WhatIf / -Confirm and idempotency
- Add
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = …)]and wrap each change inif ($PSCmdlet.ShouldProcess($target, $action)). - Predict when PowerShell prompts:
ConfirmImpactcompared with$ConfirmPreference,-Confirm,-Confirm:$false, and what happens under-NonInteractive. - Know how
-WhatIfpropagates (it sets$WhatIfPreferencein your function's scope) — and reproduce the case where it does not reachCompress-Archive. - Write idempotent changes: check the current state first; a second run changes nothing.
What: the ShouldProcess contract
| Piece | Effect |
|---|---|
[CmdletBinding(SupportsShouldProcess)] | Adds -WhatIf and -Confirm to your function (without it, -WhatIf is an error: A parameter cannot be found that matches parameter name 'WhatIf' — verified) |
$PSCmdlet.ShouldProcess($target, $action) | Returns $true if the change should happen. With -WhatIf it prints What if: Performing the operation "$action" on target "$target". and returns $false; with -Confirm it asks; with -Verbose it prints the same message as VERBOSE and returns $true |
ConfirmImpact = 'Low' | 'Medium' | 'High' | How dangerous the command is. If impact ≥ $ConfirmPreference (default High), PowerShell asks automatically |
$WhatIfPreference | -WhatIf sets it to $true in your function's scope; commands you call read it |
Why: preview before change
Bash tools each invent their own --dry-run. In PowerShell, -WhatIf is a uniform contract: every built-in cmdlet that changes state supports it, so Get-ChildItem … | Remove-Item -WhatIf always works. Your own functions join the contract with one attribute — but the guarantee is only as good as your implementation: every state change must sit behind ShouldProcess or in a command that honours the inherited $WhatIfPreference.
How: propagation — what reaches the commands you call
| Called command | Honours your -WhatIf automatically? | Verified |
|---|---|---|
Compiled cmdlets (Remove-Item, Copy-Item, New-Item, Add-Content) | Yes | Copy-Item printed What if: … "Copy File" |
Functions in the same module / script (e.g. Remove-OpsBackup called by Invoke-OpsBackup) | Yes — the dynamic scope chain finds your $WhatIfPreference | rotation printed What if: … "Remove old backup" |
Functions in another script module (e.g. Compress-Archive from Microsoft.PowerShell.Archive 1.2.7) | No — their scope chain goes to their own module and then the global scope, not to your function (they do see a preference set in the global scope — including the top level of a pwsh -File script, which runs there) | the zip was created despite -WhatIf; a test module function reported WhatIfPreference=False and wrote its file |
.NET methods ([IO.File]::Delete()) and native programs | Never | — |
So: put your own ShouldProcess call around every change, and pass -WhatIf:$WhatIfPreference (or -Confirm:$false after your own confirmation) explicitly when you call functions from other modules. Conversely, logging that must happen even in WhatIf mode needs -WhatIf:$false (or a .NET API) — verified: Add-Content in a function called with -WhatIf did not write the log.
When: ConfirmImpact vs $ConfirmPreference
| ConfirmImpact | $ConfirmPreference = High (default) | = Medium | = None |
|---|---|---|---|
| Low | no prompt | no prompt | no prompt |
| Medium (OpsKit backup) | no prompt | prompt | no prompt |
| High (e.g. delete production data) | prompt | prompt | no prompt |
-Confirm always prompts; -Confirm:$false never does. In a pwsh -NonInteractive session, a prompt is an error: Exception calling "ShouldProcess" with "2" argument(s): "PowerShell is in NonInteractive mode…" (verified) — so scheduled jobs calling High-impact commands must pass -Confirm:$false deliberately. Idempotency means “check before change”: test whether the target already is in the desired state and return early, so retries and reruns are safe.
ShouldProcess (or in cmdlets that inherit the preference) are skipped. ② “-WhatIf flows into everything I call” — not into other script modules' functions, .NET calls or native tools (verified with Compress-Archive). ③ “ConfirmImpact High means it always asks” — not if the caller set $ConfirmPreference = 'None' or passed -Confirm:$false. ④ “-WhatIf output is a reliable plan” — it is only as good as your code; OpsKit's rotation preview shows one deletion less than the real run (Module 8). ⑤ “-Force means -Confirm:$false” — only if you implement it that way.Flowchart: ShouldProcess decision
ShouldProcess decision path
Choose how Remove-OldTmp (or a High-impact command) is called and follow the decision.
-WhatIf and -Confirm are common parameters; when bound, the engine sets $WhatIfPreference / $ConfirmPreference as local variables in the function's scope. ShouldProcess reads them, compares ConfirmImpact with $ConfirmPreference, and talks to the host. A compiled cmdlet you call looks up those preference variables from the caller's scope; a script function from another module resolves variables through its own module's session state, so it never sees yours.Command table
| Syntax | Purpose | Notes |
|---|---|---|
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] | Enable -WhatIf/-Confirm | Default impact is Medium |
$PSCmdlet.ShouldProcess($target, $action) | Ask permission per change | Also 1- and 3-argument overloads |
$PSCmdlet.ShouldContinue($q, $caption) | Extra confirmation even without -Confirm | Pair with a -Force switch |
-WhatIf:$WhatIfPreference | Pass preview mode explicitly | For functions from other modules |
-WhatIf:$false | Always do this (logs) | Use sparingly and only for side-effect-free writes |
$ConfirmPreference = 'None' | Never prompt in this scope | Prefer -Confirm:$false per call |
function Remove-OldTmp {
[CmdletBinding(SupportsShouldProcess)]
param([string]$Path = './tmp', [int]$Keep = 2)
$old = Get-ChildItem -LiteralPath $Path -File -Filter 't?.txt' | Sort-Object Name -Descending | Select-Object -Skip $Keep
foreach ($f in $old) {
if ($PSCmdlet.ShouldProcess($f.Name, 'Delete old temp file')) {
Remove-Item -LiteralPath $f.FullName
"deleted $($f.Name)"
}
}
}
1..4 | ForEach-Object { Set-Content "./tmp/t$_.txt" $_ }
Remove-OldTmp -WhatIf
(Get-ChildItem ./tmp -Filter 't?.txt').Name -join ','
Remove-OldTmp
(Get-ChildItem ./tmp -Filter 't?.txt').Name -join ','
What if: Performing the operation "Delete old temp file" on target "t2.txt". What if: Performing the operation "Delete old temp file" on target "t1.txt". t1.txt,t2.txt,t3.txt,t4.txt deleted t2.txt deleted t1.txt t3.txt,t4.txt
How to verify: after -WhatIf, the listing is unchanged. Common mistake: a target string that is useless in the preview ("file"); use the name or path the operator will recognise. Production use: make -WhatIf part of every change ticket: paste its output as the plan.
Without your own ShouldProcess: cmdlets still inherit
function Clear-TmpNaive {
[CmdletBinding(SupportsShouldProcess)]
param()
Get-ChildItem ./tmp -Filter 't?.txt' | Remove-Item # no ShouldProcess call of our own
}
Clear-TmpNaive -WhatIf
What if: Performing the operation "Remove File" on target "C:\Users\labadmin\pslab\tmp\t1.txt". What if: Performing the operation "Remove File" on target "C:\Users\labadmin\pslab\tmp\t2.txt". What if: Performing the operation "Remove File" on target "C:\Users\labadmin\pslab\tmp\t3.txt". What if: Performing the operation "Remove File" on target "C:\Users\labadmin\pslab\tmp\t4.txt".
…but functions from another script module do not
# ./tmp/PropDemo/PropDemo.psm1
function Save-DataZip {
[CmdletBinding(SupportsShouldProcess)]
param([string]$Destination)
# No ShouldProcess call of our own: we rely on -WhatIf "flowing" into the commands we call
Compress-Archive -LiteralPath (Join-Path $PWD 'data/servers.csv') -DestinationPath $Destination
Copy-Item -LiteralPath (Join-Path $PWD 'data/servers.csv') -Destination ($Destination + '.csv')
}
Import-Module ./tmp/PropDemo/PropDemo.psm1 -Force Save-DataZip -Destination ./tmp/prop.zip -WhatIf "zip created anyway: $(Test-Path ./tmp/prop.zip) csv copied: $(Test-Path ./tmp/prop.zip.csv)" (Get-Command Compress-Archive).Module.ModuleType
What if: Performing the operation "Copy File" on target "Item: C:\Users\labadmin\pslab\data\servers.csv Destination: C:\Users\labadmin\pslab\tmp\prop.zip.csv". zip created anyway: True csv copied: False Manifest
Called directly with -WhatIf, Compress-Archive does honour it (verified: What if: Performing the operation "Compress-Archive" …, no file). Inside Save-DataZip, the compiled Copy-Item honoured the inherited preference; Compress-Archive — a function in a script module (the manifest's module type shows Manifest; its code is a .psm1) — created the zip. This is why Invoke-OpsBackup calls Compress-Archive only inside its own ShouldProcess block.
Logging inside a WhatIf run
function Write-RunLog {
[CmdletBinding(SupportsShouldProcess)]
param()
if ($PSCmdlet.ShouldProcess('target', 'Change')) { 'changed' }
Add-Content -LiteralPath ./tmp/run.log -Value 'run finished'
}
Write-RunLog -WhatIf
"log exists: $(Test-Path ./tmp/run.log)"
What if: Performing the operation "Change" on target "target". What if: Performing the operation "Add Content" on target "Path: C:\Users\labadmin\pslab\tmp\run.log". log exists: False
Confirm, ConfirmImpact and -NonInteractive
function Remove-Thing {
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param([string]$Name)
if ($PSCmdlet.ShouldProcess($Name, 'Remove')) { "removed $Name" }
}
Remove-Thing -Name a -Confirm:$false
$ConfirmPreference = 'None'; Remove-Thing -Name b; $ConfirmPreference = 'High'
Remove-Thing -Name c # in pwsh -NonInteractive
removed a
removed b
MethodInvocationException:
Line |
4 | if ($PSCmdlet.ShouldProcess($Name, 'Remove')) { "removed $Name" }
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Exception calling "ShouldProcess" with "2" argument(s): "PowerShell is in NonInteractive mode. Read and Prompt functionality is not available."
WhatIfPreference, -WhatIf on a function without support, idempotency
function Remove-NoSupport { [CmdletBinding()] param() 'ran' }
Remove-NoSupport -WhatIf
$WhatIfPreference = $true
New-Item ./tmp/should-not-exist.txt
Test-Path ./tmp/should-not-exist.txt
$WhatIfPreference = $false
function Set-OpsFolder {
[CmdletBinding(SupportsShouldProcess)]
param([Parameter(Mandatory)][string]$Path)
if (Test-Path -LiteralPath $Path -PathType Container) { Write-Verbose "exists: $Path"; return }
if ($PSCmdlet.ShouldProcess($Path, 'Create folder')) {
$null = New-Item -ItemType Directory -Path $Path
"created $Path"
}
}
Set-OpsFolder ./tmp/idem -Verbose
Set-OpsFolder ./tmp/idem -Verbose
Remove-Item ./tmp/idem
Remove-NoSupport: A parameter cannot be found that matches parameter name 'WhatIf'. What if: Performing the operation "Create File" on target "Destination: C:\Users\labadmin\pslab\tmp\should-not-exist.txt". False VERBOSE: Performing the operation "Create folder" on target "./tmp/idem". created ./tmp/idem VERBOSE: exists: ./tmp/idem
Goal: Prove where -WhatIf flows and fix a function that lies in preview mode. Environment: ~/pslab/tmp. Cost: a few small files.
./tmp/PropDemo/PropDemo.psm1 from the Commands tab, import it, run Save-DataZip -Destination ./tmp/prop.zip -WhatIf, and confirm that the zip exists.function Save-DataZip {
[CmdletBinding(SupportsShouldProcess)]
param([string]$Destination)
if ($PSCmdlet.ShouldProcess($Destination, 'Create archive')) {
Compress-Archive -LiteralPath (Join-Path $PWD 'data/servers.csv') -DestinationPath $Destination -Confirm:$false
Copy-Item -LiteralPath (Join-Path $PWD 'data/servers.csv') -Destination ($Destination + '.csv')
}
}
Remove ./tmp/prop.zip, re-import with -Force, run with -WhatIf: one “What if” line, no files. Run without: both files (verified on 7.6.10).
Import-Module ./OpsKit/OpsKit.psd1 -Force "caller EAP after import: $ErrorActionPreference" Get-Item ./nope; 'caller continued (module Stop did not leak)'
caller EAP after import: Continue Get-Item: Cannot find path 'C:\Users\labadmin\pslab\nope' because it does not exist. caller continued (module Stop did not leak)
Remove-Module PropDemo -ErrorAction Ignore; Remove-Item ./tmp/PropDemo, ./tmp/prop.zip, ./tmp/prop.zip.csv, ./tmp/t?.txt -Recurse -ErrorAction IgnoreCase 1: a “dry run” that deleted the archive bucket
Problem: An engineer ran an internal Invoke-Retention -WhatIf before a change window; the preview looked right, and the real data was already gone. Root cause: the function deleted blobs with a function from another module (and in another version with a .NET SDK call) without its own ShouldProcess; neither saw -WhatIf. Fix: every state change behind ShouldProcess; a Pester test (Lesson 8) that runs the function with -WhatIf and asserts nothing changed — the same check this lesson's failure-injection lab does.
Case 2: a scheduled task that “hung” on Monday mornings
Problem: A weekly purge task never finished. Root cause: the purge function had ConfirmImpact = 'High'; the task ran pwsh -File without -NonInteractive, so it waited for a confirmation nobody could give. Fix: -NonInteractive (fail fast instead of hang) and an explicit -Confirm:$false in the task's command line — a deliberate, reviewable decision.
Case 3: reruns that doubled the data
Problem: A provisioning script that failed halfway was rerun and created duplicate DNS records and users. Root cause: “create” steps without “exists?” checks. Fix: idempotent steps (Get first, Set only on difference). OpsKit's backup is idempotent by name: the same timestamp is never written twice (Module 8).
Common errors and fixes
A parameter cannot be found that matches parameter name 'WhatIf'
Fix: add SupportsShouldProcess to [CmdletBinding()]; the function must be advanced.
-WhatIf prints nothing for my function
Cause: no ShouldProcess call and no inheriting cmdlet inside — or the change happens via .NET/native/other-module code. Fix: wrap the change in if ($PSCmdlet.ShouldProcess(…)).
Exception calling "ShouldProcess" … NonInteractive mode
Cause: a confirmation was required in a non-interactive session. Fix: pass -Confirm:$false deliberately, or lower the command's impact if it was over-classified.
My log file is empty after a -WhatIf run
Cause: Add-Content/Out-File inherited WhatIf. Fix: -WhatIf:$false on the log write, or a .NET append as in Write-OpsLog.
1. Preview deleting every *.tmp file under ~/pslab without deleting anything.
Get-ChildItem ~/pslab -Recurse -Filter *.tmp -File | Remove-Item -WhatIf
2. Write the skeleton of a High-impact function with a -Force switch that skips the prompt.
function Remove-OpsTenant {
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param([Parameter(Mandatory)][string]$Name, [switch]$Force)
if ($Force -and -not $PSBoundParameters.ContainsKey('Confirm')) { $ConfirmPreference = 'None' }
if ($PSCmdlet.ShouldProcess($Name, 'Remove tenant')) { <# change #> }
}Verified pattern on 7.6.10: with -Force the function ran without prompting; -WhatIf still wins because it is checked first.
Your team wants a single -DryRun switch on all deployment scripts instead of -WhatIf, “because -WhatIf is unreliable”. What do you recommend?
Keep the standard -WhatIf: operators and tools already know it, built-in cmdlets honour it, and it composes through pipelines. Its unreliability is an implementation problem — fix it with rules: every change inside ShouldProcess; explicit -WhatIf:$WhatIfPreference when calling functions from other modules; never rely on propagation into .NET or native calls; and a test that runs each script with -WhatIf against a sandbox and asserts no state changed. A custom -DryRun would need the same discipline and would not get inheritance into cmdlets for free.
Verified teaching videos
Official documentation
- Everything you wanted to know about ShouldProcess · about_Functions_CmdletBindingAttribute
- How to request confirmations · about_Preference_Variables ($ConfirmPreference, $WhatIfPreference)
Video storyboard (about 90 seconds)
Visual: a function with a red “change” box guarded by a gate labelled ShouldProcess.
Narration: every change goes through the gate.
Visual: -WhatIf turns the gate into a printer of “What if:” lines; Copy-Item obeys, Compress-Archive walks around the gate and creates a zip.
Narration: cmdlets inherit WhatIf; functions from other modules may not. Verify.
Visual: a dial ConfirmImpact Low/Medium/High against a threshold $ConfirmPreference; a prompt pops up when the needle crosses.
Narration: impact versus preference decides whether to ask.
Visual: running the same command twice; the second time a green “already done”.
Narration: check before change, so reruns are safe.
Module 7 · Retries, timeouts and structured logging
- Implement
Invoke-OpsRetry: exponential backoff, “equal jitter”, a cap, and retry only listed transient exception types. - Explain why non-terminating errors are never retried and why permanent errors must not be.
- Bound waiting with
Wait-Job -Timeout, aCancellationTokenSource, and web-cmdlet timeouts — and know that-OperationTimeoutSecondsdid not stop a slow first response while-TimeoutSecdid (verified). - Write JSON-lines logs with
ConvertTo-Json -Compress, query them withConvertFrom-Json, and know the caveats ofStart-Transcript.
What: transient vs permanent
| Retry? | Examples | Why |
|---|---|---|
| Yes (transient) | File locked by another process (IOException), timeouts (TimeoutException, TaskCanceledException), HTTP 429/503, a DNS blip | The same call can succeed a moment later |
| No (permanent) | File not found, access denied, validation errors, HTTP 400/401/404, bugs | Retrying only delays the failure and hides it; with credentials it can lock accounts |
Why: backoff and jitter
Retrying immediately in a tight loop hammers a struggling service. Exponential backoff doubles the wait each time (500 ms, 1 s, 2 s …) up to a cap. Jitter randomises each wait so that 200 clients that failed together do not retry together. OpsKit uses “equal jitter”: the delay before retry n is a random value between cap/2 and cap, where cap = min(MaxDelayMs, BaseDelayMs × 2^(n−1)). Always bound the total: a maximum number of attempts and, for external calls, a per-attempt timeout.
How: the rules Invoke-OpsRetry encodes
- Retry only terminating errors — so the script block must use
-ErrorAction Stop. A non-terminating error is just written and the block “succeeds” (verified below). - Match the exception and its inner exceptions against
-RetryOntypes (wrappers such asMethodInvocationExceptionare common). - On the last attempt or a non-retryable error, re-raise the original ErrorRecord with
$PSCmdlet.ThrowTerminatingError(), so callers can still catch by type and id. - Expose an
-OnRetryhook so the caller can log and clean up (OpsKit deletes the partial archive there, Module 8), and a-Seedfor reproducible tests.
When: timeouts and logs
| Need | Tool | Notes |
|---|---|---|
| Bound a block of PowerShell | Start-ThreadJob + Wait-Job -Timeout + Stop-Job | Wait-Job returns nothing on timeout; the job keeps running until stopped |
| Bound a .NET async call | [System.Threading.CancellationTokenSource]::new([TimeSpan]) | Pass .Token; catch TaskCanceledException / OperationCanceledException |
| Bound a web call | Invoke-RestMethod -TimeoutSec (alias of -ConnectionTimeoutSeconds) | On 7.6.10 it cut off a response that never arrived after 2 s; -OperationTimeoutSeconds did not (it governs reads of an ongoing response) |
| Machine-readable run record | JSON lines: [ordered]@{…} | ConvertTo-Json -Compress appended per event | One event per line; append-only; grep/ConvertFrom-Json/any log shipper can read it |
| Human-readable session record | Start-Transcript | Caveat: output of native programs that write straight to the console is not in the transcript (verified); may capture secrets; one per session |
-ErrorAction Stop. ③ “Wait-Job -Timeout kills the job” — it only stops waiting; call Stop-Job. ④ “-OperationTimeoutSeconds is the total request timeout” — not on 7.6.10 (a server that never answered was waited for 5.2 s with a 2 s value). ⑤ “A transcript is a log” — it is a text dump, unstructured, and misses native console output. ⑥ “Log lines should be pretty JSON” — one compact object per line, or line-based tools break.Timeline: backoff with equal jitter (BaseDelayMs = 200, seed 42)
Diagram: a JSON-lines log as an event stream
Retry timeline
Choose what the script block does and watch Invoke-OpsRetry decide on each attempt. Delays are the real values from the 7.6.10 runs.
Invoke-OpsRetry runs the block with & inside try. A terminating error lands in catch; the function walks $_.Exception and its InnerException chain, tests each against -RetryOn with -is, computes the jittered delay with System.Random, calls the -OnRetry hook, sleeps and loops. A non-terminating error never reaches catch, so the loop returns after the first attempt.Command table
| Command | Purpose | Notes |
|---|---|---|
Invoke-OpsRetry -RetryOn ([System.IO.IOException]) { … -ErrorAction Stop } | Retry transient errors | OpsKit v0.3; -MaxAttempts, -BaseDelayMs, -MaxDelayMs, -OnRetry, -Seed |
Start-ThreadJob { … } | Wait-Job -Timeout 5 | Bounded wait | Then Stop-Job, Remove-Job |
[Threading.CancellationTokenSource]::new([TimeSpan]::FromSeconds(5)) | Cancel .NET async work | Dispose it |
Invoke-RestMethod -TimeoutSec 10 -MaximumRetryCount 3 -RetryIntervalSec 2 | Web timeout and built-in retries | Built-in retries cover HTTP 304/400–599 responses; Lesson 7 |
ConvertTo-Json -Compress -Depth 4 | One-line JSON | Always set -Depth for nested data |
Start-Transcript -Path f -UseMinimalHeader / Stop-Transcript | Session text record | Not a substitute for structured logs |
Invoke-OpsRetry (OpsKit/Public/Invoke-OpsRetry.ps1)
function Invoke-OpsRetry {
<#
.SYNOPSIS
Runs a script block and retries it on transient errors with exponential backoff and jitter.
.DESCRIPTION
Only terminating errors are retried, so use -ErrorAction Stop inside the script block.
Delay before retry n = random value between cap/2 and cap, where
cap = min(MaxDelayMs, BaseDelayMs * 2^(n-1)) ("equal jitter").
.EXAMPLE
Invoke-OpsRetry -RetryOn ([System.IO.IOException]) { Get-Content ./x.log -ErrorAction Stop }
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)][scriptblock]$ScriptBlock,
[ValidateRange(1, 20)][int]$MaxAttempts = 3,
[ValidateRange(0, 60000)][int]$BaseDelayMs = 500,
[ValidateRange(0, 300000)][int]$MaxDelayMs = 10000,
[type[]]$RetryOn = @([System.Exception]),
[scriptblock]$OnRetry,
[int]$Seed = -1
)
$random = if ($Seed -ge 0) { [System.Random]::new($Seed) } else { [System.Random]::new() }
for ($attempt = 1; ; $attempt++) {
try {
return (& $ScriptBlock)
}
catch {
$record = $_
# Look through wrapper exceptions (MethodInvocationException, AggregateException ...).
$chain = for ($e = $record.Exception; $e; $e = $e.InnerException) { $e }
$transient = foreach ($e in $chain) { foreach ($t in $RetryOn) { if ($e -is $t) { $e } } }
if (-not $transient -or $attempt -ge $MaxAttempts) {
Write-Verbose ("attempt {0}/{1} failed, giving up: {2}" -f $attempt, $MaxAttempts, $record.Exception.Message)
$PSCmdlet.ThrowTerminatingError($record)
}
$cap = [math]::Min($MaxDelayMs, $BaseDelayMs * [math]::Pow(2, $attempt - 1))
$delay = [int]($cap / 2 + $random.NextDouble() * $cap / 2)
Write-Verbose ("attempt {0}/{1} failed ({2}); retrying in {3} ms" -f $attempt, $MaxAttempts, @($transient)[0].GetType().Name, $delay)
if ($OnRetry) { & $OnRetry $attempt $delay $record }
Start-Sleep -Milliseconds $delay
}
}
}
Transient error: retried, then success
Import-Module ./OpsKit/OpsKit.psd1 -Force
$script:calls = 0
$sw = [System.Diagnostics.Stopwatch]::StartNew()
Invoke-OpsRetry -MaxAttempts 5 -BaseDelayMs 200 -Seed 42 -RetryOn ([System.TimeoutException]) -Verbose {
$script:calls++
if ($script:calls -lt 4) { throw [System.TimeoutException]::new("call $script:calls timed out") }
"succeeded on call $script:calls"
}
"elapsed ~{0:N1} s" -f $sw.Elapsed.TotalSeconds
VERBOSE: attempt 1/5 failed (TimeoutException); retrying in 167 ms VERBOSE: attempt 2/5 failed (TimeoutException); retrying in 228 ms VERBOSE: attempt 3/5 failed (TimeoutException); retrying in 450 ms succeeded on call 4 elapsed ~1.0 s
How to verify: each delay lies in its window (100–200, 200–400, 400–800 ms). Common mistake: forgetting that “elapsed” includes the work itself — set a per-attempt timeout for external calls. Production use: retry only the types you have seen be transient in your logs.
Permanent and non-terminating errors are not retried
try {
Invoke-OpsRetry -MaxAttempts 5 -RetryOn ([System.TimeoutException]) -Verbose {
Get-Item ./data/nope.txt -ErrorAction Stop
}
} catch { "not retried, caught: $($_.Exception.GetType().Name)" }
Invoke-OpsRetry -MaxAttempts 3 -BaseDelayMs 100 -Verbose { Get-Item ./data/nope.txt }
'non-terminating error: no retry happened, and the caller continues'
VERBOSE: attempt 1/5 failed, giving up: Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist. not retried, caught: ItemNotFoundException Get-Item: Cannot find path 'C:\Users\labadmin\pslab\data\nope.txt' because it does not exist. non-terminating error: no retry happened, and the caller continues
Timeouts
$job = Start-ThreadJob { Start-Sleep -Seconds 10; 'finished' }
$done = $job | Wait-Job -Timeout 2
if (-not $done) {
"timed out after 2 s; state = $($job.State)"
$job | Stop-Job
"after Stop-Job: $($job.State)"
}
$job | Remove-Job
$cts = [System.Threading.CancellationTokenSource]::new([TimeSpan]::FromMilliseconds(500))
try {
[System.Threading.Tasks.Task]::Delay(5000, $cts.Token).GetAwaiter().GetResult()
}
catch [System.Threading.Tasks.TaskCanceledException] {
"cancelled after 500 ms: $($_.Exception.GetType().Name)"
}
finally { $cts.Dispose() }
timed out after 2 s; state = Running after Stop-Job: Stopped cancelled after 500 ms: TaskCanceledException
Web timeouts against a slow local mock API
# Mock API on localhost: every request is answered after 5 seconds
$server = Start-ThreadJob {
$l = [System.Net.HttpListener]::new(); $l.Prefixes.Add('http://localhost:8765/'); $l.Start()
1..2 | ForEach-Object { $ctx = $l.GetContext(); Start-Sleep -Seconds 5; $ctx.Response.Close() }
$l.Stop()
}
Start-Sleep -Milliseconds 800
foreach ($opt in @{ OperationTimeoutSeconds = 2 }, @{ TimeoutSec = 2 }) {
$sw = [System.Diagnostics.Stopwatch]::StartNew()
try {
$null = Invoke-RestMethod http://localhost:8765/slow @opt
"{0,-26} returned after {1:N1} s" -f "-$($opt.Keys)", $sw.Elapsed.TotalSeconds
}
catch {
"{0,-26} {1} after {2:N1} s" -f "-$($opt.Keys)", $_.Exception.GetType().Name, $sw.Elapsed.TotalSeconds
}
}
$server | Wait-Job -Timeout 15 | Remove-Job
-OperationTimeoutSeconds returned after 5.2 s -TimeoutSec TaskCanceledException after 2.0 s
The exception message of the second call was The request was canceled due to the configured HttpClient.Timeout of 2 seconds elapsing. localhost is used because an HttpListener prefix of http://127.0.0.1:… may need a URL reservation on Windows.
Structured logging: Write-OpsLog (OpsKit/Private/Write-OpsLog.ps1)
function Write-OpsLog {
# Appends one JSON object per line (JSON Lines) to $Path. Never throws: logging must not
# turn a successful operation into a failure, so a log write error becomes a warning.
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][ValidateSet('debug', 'info', 'warning', 'error')][string]$Level,
[Parameter(Mandatory)][string]$Event,
[hashtable]$Data = @{},
[string]$RunId = ''
)
$record = [ordered]@{
ts = [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ss.fffZ')
level = $Level
event = $Event
runId = $RunId
}
foreach ($key in $Data.Keys | Sort-Object) { $record[$key] = $Data[$key] }
$Path = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) # .NET resolves relative paths against the process folder, not $PWD
$line = ($record | ConvertTo-Json -Compress -Depth 4) + "`n"
try {
$dir = Split-Path -Parent $Path
if (-not [System.IO.Directory]::Exists($dir)) { $null = [System.IO.Directory]::CreateDirectory($dir) }
# .NET API on purpose: Add-Content would honour -WhatIf and silently skip the log line.
[System.IO.File]::AppendAllText($Path, $line, [System.Text.UTF8Encoding]::new($false))
}
catch {
Write-Warning "OpsKit: could not write log ${Path}: $($_.Exception.Message)"
}
}
Design choices: UTC ISO-8601 timestamps with milliseconds; a short runId to group events; sorted extra keys for stable diffs; the .NET append so -WhatIf runs are still logged (Module 6); and a logger that never throws.
Start-Transcript caveat
# ./scripts/Show-Transcript.ps1 Start-Transcript -Path ./tmp/transcript.txt -UseMinimalHeader | Out-Null 'success output' Write-Host 'host output' Write-Verbose 'verbose (not enabled)' cmd /c echo native-output Stop-Transcript | Out-Null
pwsh -NoProfile -File ./scripts/Show-Transcript.ps1 '--- transcript file:' Get-Content ./tmp/transcript.txt
success output host output native-output --- transcript file: ********************** PowerShell transcript start Start time: 20261124210504 ********************** success output host output ********************** PowerShell transcript end End time: 20261124210504 **********************
The console showed native-output; the transcript has an empty line in its place. Pipe native output through PowerShell (cmd /c echo x | Out-Host or capture it) if it must be recorded.
Goal: Use Invoke-OpsRetry and Write-OpsLog-style events on a real transient failure. Environment: ~/pslab, OpsKit 0.3.0. Cost: none.
Import-Module ./OpsKit/OpsKit.psd1 -Force
$p = (Resolve-Path ./data/servers.csv).Path
$lock = Start-ThreadJob -ArgumentList $p { param($p) $fs = [IO.File]::Open($p, 'Open', 'Read', 'None'); Start-Sleep -Milliseconds 900; $fs.Dispose() }
Start-Sleep -Milliseconds 200
Invoke-OpsRetry -MaxAttempts 5 -BaseDelayMs 300 -RetryOn ([System.IO.IOException]) -Verbose {
(Import-Csv -LiteralPath $p -ErrorAction Stop).Count
}
$lock | Wait-Job | Remove-Job
VERBOSE: attempt 1/5 failed (IOException); retrying in 165 ms VERBOSE: attempt 2/5 failed (IOException); retrying in 566 ms VERBOSE: attempt 3/5 failed (IOException); retrying in 624 ms 12
If you see no retry, the lock was released before the first read — increase the sleep inside the thread job.
Write-OpsLog is not exported, so use the module scope to call it — handy for experiments, not for production code):
& (Get-Module OpsKit) { Write-OpsLog -Path ./tmp/lab.jsonl -Level info -Event 'lab.test' -Data @{ answer = 42 } }
Get-Content ./tmp/lab.jsonl | ConvertFrom-Json | Format-Table ts, level, event, answer
ts level event answer -- ----- ----- ------ 11/25/2026 2:29:33 AM info lab.test 42
A real bug found while writing this lab: the first version of Write-OpsLog passed ./tmp/lab.jsonl straight to [IO.File]::AppendAllText, which resolves relative paths against the process working folder ([Environment]::CurrentDirectory), not PowerShell's $PWD — the log went somewhere else and Get-Content failed with Cannot find path. The fix is the GetUnresolvedProviderPathFromPSPath() line. Rule: convert every path to a full provider path before handing it to .NET.
Start-Sleep 10 in a thread job and stop it after 2 s as in the Commands tab.Remove-Item ./tmp/lab.jsonl, ./tmp/transcript.txt -ErrorAction IgnoreCase 1: the retry storm
Problem: After a 30-second database failover, 400 worker scripts retried every second without jitter and kept the database pinned at 100% CPU for 20 minutes. Root cause: fixed interval, no jitter, no cap on attempts. Fix: exponential backoff with jitter and a maximum; a circuit breaker at the caller level for long outages.
Case 2: retries that locked out a service account
Problem: A sync job retried a failed login 5 times per run, every 5 minutes. The directory locked the account. Root cause: catch { retry } without types — authentication failures are permanent. Fix: -RetryOn only network/timeout types; authentication errors fail immediately with a clear id.
Case 3: “which run deleted that file?”
Problem: Several overlapping runs wrote interleaved text logs; nobody could tell which run removed a backup. Root cause: free-text logs without run identifiers. Fix: JSON lines with runId, event and the affected file (OpsKit's backup.removed event) — then Get-Content log | ConvertFrom-Json | Where-Object event -eq 'backup.removed' answers it in one line.
Common errors and fixes
My retry wrapper never retries
Cause: the block's errors are non-terminating, or the exception type (or its inner exception) is not in -RetryOn.
try { <block> } catch { $e = $_.Exception; while ($e) { $e.GetType().FullName; $e = $e.InnerException } }ConvertTo-Json output is truncated with "System.Collections.Hashtable"
Cause: default -Depth is 2; deeper levels are converted with ToString().
@{ a = @{ b = @{ c = @{ d = 1 } } } } | ConvertTo-Json -Compress
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{"a":{"b":{"c":"System.Collections.Hashtable"}}}
Fix: -Depth 4 or more.
My log file is not where I told it to be
Cause: a relative path passed to a .NET method resolves against [Environment]::CurrentDirectory, which Set-Location does not change. Fix: $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) or Join-Path $PWD … first (see the Lab tab).
Wait-Job -Timeout returned, but the work is still running
Fix: Stop-Job then Remove-Job; for thread jobs, make the work itself cancellable when possible.
The request was canceled due to the configured HttpClient.Timeout
Cause: -TimeoutSec elapsed. Fix: decide if it is transient (retry with backoff) or if the endpoint is simply slow (raise the timeout).
1. Count log events per level in ~/pslab/backups/opskit-backup.jsonl.
Get-Content ~/pslab/backups/opskit-backup.jsonl | ConvertFrom-Json | Group-Object level -NoElement
2. Compute the four delay windows for BaseDelayMs 500, MaxDelayMs 3000.
1..4 | ForEach-Object { $cap = [math]::Min(3000, 500 * [math]::Pow(2, $_ - 1)); '{0}: {1}-{2} ms' -f $_, ($cap / 2), $cap }1: 250–500, 2: 500–1000, 3: 1000–2000, 4: 1500–3000 (capped).
An API sometimes takes 90 s to answer and sometimes never answers. Your script calls it with no timeout inside a 3-attempt retry. Calculate the worst case and redesign.
With no timeout a call that never answers blocks forever (or until the HttpClient default of 100 s, then the retry starts again): worst case ≈ 3 × 100 s plus backoff — about 5 minutes, or forever with other clients. Redesign: per-attempt -TimeoutSec slightly above the normal p99 (e.g. 120 s if 90 s is legitimate), retry only on timeout/5xx/429, max 3 attempts with jittered backoff, and an overall deadline checked before each attempt (stop if less than one timeout remains). Log each attempt as an event with its duration.
Verified teaching videos
No verified video was found on retry/backoff patterns or JSON-lines logging in PowerShell. Use this module and the documentation.
Official documentation
- Invoke-RestMethod (-TimeoutSec, -OperationTimeoutSeconds, -MaximumRetryCount) · Wait-Job
- Start-Transcript
Video storyboard (about 90 seconds)
Visual: 200 clients failing at once and retrying in lockstep; a server icon turns red.
Narration: retries without jitter turn a blip into an outage.
Visual: the retry timeline with growing, randomised wait bars.
Narration: back off exponentially, randomise, and stop after a few attempts.
Visual: two errors at a gate: “locked file” passes into the retry loop, “not found” is sent straight out.
Narration: retry transient errors only.
Visual: a wall of console text collapses into tidy JSON lines with runId; a query picks out one run.
Narration: log events, not prose.
Module 8 · OpsKit v0.3: Invoke-OpsBackup with rotation, -WhatIf, retries and logs
- Read and run
Invoke-OpsBackupandRemove-OpsBackup; reproduce their-WhatIf,-Verbose, idempotent-rerun, rotation and retry behaviour. - Explain the partial archive trap:
Compress-Archivewithout Stop wrote a 15-entry zip and$?was$true(verified). - Wrap a module command in a scheduler-friendly script with Stop at the boundary and distinct exit codes (0–4).
- Diagnose “the error was not caught” and “the script reported success but failed” with the troubleshooting tree.
What: the v0.3 commands
| Command | Does | Safety features |
|---|---|---|
Invoke-OpsBackup | Zips the top-level items of ~/pslab/data (minus Backup.Exclude patterns) into ~/pslab/backups/pslab-data-yyyyMMdd-HHmmss.zip, then rotates | Guard clause with id OpsKit.BackupSourceNotFound; idempotent by name (an existing archive is never overwritten: warning + status Exists); ShouldProcess around the only write; IOException retried via Invoke-OpsRetry; partial archive deleted after each failed attempt; JSON-lines events backup.started/retry/created/failed; returns one result object |
Remove-OpsBackup | Keeps the newest -Keep archives (config Backup.Keep = 7), deletes the rest | Only matches pslab-data-*.zip; [ValidateRange(1,365)] so -Keep 0 is impossible; ShouldProcess per file; event backup.removed |
Invoke-OpsRetry | Generic retry (Module 7) | Retries listed types only; rethrows the original error |
scripts/Invoke-NightlyBackup.ps1 | The scheduler entry point | Strict mode, Stop, native preference on; verifies the archive by opening it; exit codes 0 ok · 1 backup failed · 2 config missing · 3 source missing · 4 archive invalid; one greppable stderr line |
Why: each design decision maps to an incident
| Decision | Prevents | Module |
|---|---|---|
Compress-Archive … -ErrorAction Stop inside retry | A “successful” backup that silently lacks a locked file — reproduced below: 15 of 16 entries, $? = True | 1, 2 |
Delete the partial archive in -OnRetry and in catch | A retry failing with “file already exists”, or a corrupt zip left for the next run's “idempotent” skip | 7 |
Own ShouldProcess around Compress-Archive | Creating archives during -WhatIf (verified: -WhatIf does not reach Compress-Archive) | 6 |
ThrowTerminatingError with stable ids | Callers matching English messages; the error appearing to come from inside OpsKit | 2 |
Stop + try/catch + exit N in the wrapper | “Script reported success” — reproduced below with a naive wrapper: error printed, exit=0 | 1, 2, 3 |
$env:OPSKIT_HOME | Tests touching real backups | 0, integrated lab |
How: the run path
- Read config; resolve
Source,Destination,Keep,LogPath(parameters override config). - Guard: source folder exists, else log
backup.failedandThrowTerminatingError. - Compute the archive name from
-Timestamp(default now). Exists → warning, statusExists(idempotent). ShouldProcess→ if-WhatIf, statusWhatIf, nothing written.- Compress with retry on
IOException; after each failure logbackup.retryand delete the partial zip. - Log
backup.createdwith size and attempts; on final failure logbackup.failed, clean up, rethrow. - Rotate with
Remove-OpsBackup— it inherits-WhatIf/-Confirmbecause it is in the same module. - Return
[pscustomobject]@{ Archive; Items; SizeKB; Attempts; Removed; RunId; Status }.
When: run it how?
- Interactively:
Invoke-OpsBackup -WhatIffirst, then without. - Scheduled:
pwsh -NoProfile -NonInteractive -File ~/pslab/scripts/Invoke-NightlyBackup.ps1(Task Scheduler, cron, a CI schedule). Alert on a non-zero exit code; read the JSON log for details. - Known limitation by design:
-WhatIfpreviews the rotation without the archive it would have created, so it shows one deletion less than the real run (verified: 2 vs 3). Honest previews need the code to account for the pending change — a good exercise.
$? stays $true (verified). ② “The module throws, so my script stops” — ThrowTerminatingError is statement-terminating; a naive wrapper printed “Backup finished” and exited 0 (verified). ③ “Rotation by LastWriteTime is safer” — timestamps change when files are copied; the sortable name is the source of truth here. ④ “Logging may fail the backup” — Write-OpsLog never throws; a logging failure becomes a warning. ⑤ “An existing archive with the right name is a good archive” — the wrapper verifies it (corrupt archive → exit 4 in the integrated lab).Flowchart: Invoke-OpsBackup
Backup run path
Choose a situation and follow Invoke-OpsBackup (and the nightly wrapper) step by step. Below it, the interactive troubleshooting tree.
Interactive troubleshooting tree: the error was not caught / the script reported success but failed
Command table
| Command | Purpose | Notes |
|---|---|---|
Invoke-OpsBackup -WhatIf | Preview | Shows the archive and the rotation deletions |
Invoke-OpsBackup -Timestamp '2026-11-24 10:00:00' | Deterministic name | Used in all examples; production uses the default (now) |
Invoke-OpsBackup -Keep 30 -MaxAttempts 4 -BaseDelayMs 200 | Override config / retry | Validated ranges |
Remove-OpsBackup -Keep 7 -WhatIf | Rotation only | Default Keep from config |
Get-Content ~/pslab/backups/opskit-backup.jsonl | ConvertFrom-Json | Read the log | Group by event, filter by runId |
pwsh -NoProfile -NonInteractive -File ./scripts/Invoke-NightlyBackup.ps1 | Scheduled run | Check $LASTEXITCODE |
OpsKit/Public/Invoke-OpsBackup.ps1
function Invoke-OpsBackup {
<#
.SYNOPSIS
Zips ~/pslab/data into ~/pslab/backups, keeps the newest N archives and logs as JSON lines.
.DESCRIPTION
Settings come from opskit.config.psd1 (Backup.Destination, Backup.Keep, Backup.Exclude);
parameters override them. Supports -WhatIf / -Confirm, which also reach the rotation step.
Locked files (IOException) are retried with exponential backoff.
.EXAMPLE
Invoke-OpsBackup -WhatIf
.EXAMPLE
Invoke-OpsBackup -Timestamp '2026-11-24 10:00:00' -Verbose
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
[OutputType([pscustomobject])]
param(
[string]$Source,
[string]$Destination,
[ValidateRange(1, 365)][int]$Keep,
[datetime]$Timestamp = (Get-Date),
[ValidateRange(1, 10)][int]$MaxAttempts = 3,
[ValidateRange(0, 60000)][int]$BaseDelayMs = 500,
[string]$LogPath
)
$cfg = Get-OpsConfig
if (-not $Source) { $Source = Resolve-OpsPath '~/pslab/data' }
if (-not $Destination) { $Destination = Resolve-OpsPath $cfg.Backup.Destination }
if (-not $PSBoundParameters.ContainsKey('Keep')) { $Keep = $cfg.Backup.Keep }
if (-not $LogPath) { $LogPath = Join-Path $Destination 'opskit-backup.jsonl' }
$runId = [guid]::NewGuid().ToString('n').Substring(0, 8)
$log = @{ Path = $LogPath; RunId = $runId }
# Guard clause: fail fast, with a specific error id the caller can test.
if (-not (Test-Path -LiteralPath $Source -PathType Container)) {
Write-OpsLog @log -Level error -Event 'backup.failed' -Data @{ reason = 'SourceNotFound'; source = $Source }
$PSCmdlet.ThrowTerminatingError([System.Management.Automation.ErrorRecord]::new(
[System.IO.DirectoryNotFoundException]::new("Backup source not found: $Source"),
'OpsKit.BackupSourceNotFound', [System.Management.Automation.ErrorCategory]::ObjectNotFound, $Source))
}
$zip = Join-Path $Destination ('pslab-data-{0:yyyyMMdd-HHmmss}.zip' -f $Timestamp)
$items = @(Get-ChildItem -LiteralPath $Source -Force | Where-Object {
$name = $_.Name
-not ($cfg.Backup.Exclude | Where-Object { $name -like $_ })
})
$result = [pscustomobject]@{
Archive = $zip; Items = $items.Count; SizeKB = $null; Attempts = 0; Removed = 0; RunId = $runId; Status = 'Skipped'
}
if (Test-Path -LiteralPath $zip) {
# Idempotent: the same timestamp was already backed up; do not overwrite it.
Write-Warning "Backup already exists, nothing to do: $zip"
$result.Status = 'Exists'
}
elseif ($PSCmdlet.ShouldProcess($zip, "Create backup of $Source ($($items.Count) items)")) {
Write-OpsLog @log -Level info -Event 'backup.started' -Data @{ source = $Source; archive = $zip; items = $items.Count }
try {
if (-not (Test-Path -LiteralPath $Destination)) { $null = New-Item -ItemType Directory -Path $Destination }
Invoke-OpsRetry -MaxAttempts $MaxAttempts -BaseDelayMs $BaseDelayMs -RetryOn ([System.IO.IOException]) -OnRetry {
param($attempt, $delay, $err)
$result.Attempts = $attempt
Write-OpsLog @log -Level warning -Event 'backup.retry' -Data @{ attempt = $attempt; delayMs = $delay; error = $err.Exception.Message }
# Compress-Archive may leave a partial archive behind; never retry on top of it.
if (Test-Path -LiteralPath $zip) { Remove-Item -LiteralPath $zip -WhatIf:$false }
} -ScriptBlock {
Compress-Archive -LiteralPath $items.FullName -DestinationPath $zip -ErrorAction Stop
}
$result.Attempts++
$result.SizeKB = [math]::Round((Get-Item -LiteralPath $zip).Length / 1KB, 1)
$result.Status = 'Created'
Write-OpsLog @log -Level info -Event 'backup.created' -Data @{ archive = $zip; sizeKB = $result.SizeKB; attempts = $result.Attempts }
}
catch {
Write-OpsLog @log -Level error -Event 'backup.failed' -Data @{ reason = $_.FullyQualifiedErrorId; error = $_.Exception.Message }
if (Test-Path -LiteralPath $zip) { Remove-Item -LiteralPath $zip -WhatIf:$false }
$PSCmdlet.ThrowTerminatingError($_)
}
}
else {
$result.Status = 'WhatIf'
}
# Rotation inherits -WhatIf / -Confirm automatically (same module, same call chain).
$removed = @(Remove-OpsBackup -Destination $Destination -Keep $Keep -LogPath $LogPath -RunId $runId)
$result.Removed = $removed.Count
$result
}
OpsKit/Public/Remove-OpsBackup.ps1
function Remove-OpsBackup {
<#
.SYNOPSIS
Deletes old backup archives, keeping the newest -Keep files.
.EXAMPLE
Remove-OpsBackup -Keep 7 -WhatIf
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
[OutputType([System.IO.FileInfo])]
param(
[ValidateRange(1, 365)][int]$Keep,
[string]$Destination,
[string]$LogPath,
[string]$RunId = ([guid]::NewGuid().ToString('n').Substring(0, 8))
)
$cfg = Get-OpsConfig
if (-not $PSBoundParameters.ContainsKey('Keep')) { $Keep = $cfg.Backup.Keep }
if (-not $Destination) { $Destination = Resolve-OpsPath $cfg.Backup.Destination }
if (-not $LogPath) { $LogPath = Join-Path $Destination 'opskit-backup.jsonl' }
if (-not (Test-Path -LiteralPath $Destination -PathType Container)) {
Write-Verbose "no backup folder yet: $Destination"
return
}
# The name embeds the timestamp (yyyyMMdd-HHmmss), so a name sort is a time sort.
$old = Get-ChildItem -LiteralPath $Destination -Filter 'pslab-data-*.zip' -File |
Sort-Object Name -Descending |
Select-Object -Skip $Keep
foreach ($file in $old) {
if ($PSCmdlet.ShouldProcess($file.Name, 'Remove old backup')) {
Remove-Item -LiteralPath $file.FullName
Write-OpsLog -Path $LogPath -Level info -Event 'backup.removed' -RunId $RunId -Data @{ file = $file.Name }
$file
}
}
}
OpsKit/Public/Get-OpsConfig.ps1 (changed) and OpsKit/Private/Resolve-OpsPath.ps1 (new)
function Get-OpsConfig {
<#
.SYNOPSIS
Reads opskit.config.psd1 safely (no code execution).
#>
[CmdletBinding()]
[OutputType([hashtable])]
param(
[string]$Path = (Resolve-OpsPath '~/pslab/data/opskit.config.psd1')
)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
$err = [System.Management.Automation.ErrorRecord]::new(
[System.IO.FileNotFoundException]::new("OpsKit config not found: $Path", $Path),
'OpsKit.ConfigNotFound',
[System.Management.Automation.ErrorCategory]::ObjectNotFound,
$Path)
$PSCmdlet.ThrowTerminatingError($err)
}
Import-PowerShellDataFile -LiteralPath $Path
}
function Resolve-OpsPath {
# Maps '~/pslab/...' (as written in opskit.config.psd1) to the OpsKit root.
# The root is $env:OPSKIT_HOME when set (tests, CI), otherwise ~/pslab.
[CmdletBinding()]
[OutputType([string])]
param([Parameter(Mandatory)][string]$Path)
$root = if ($env:OPSKIT_HOME) { $env:OPSKIT_HOME } else { Join-Path $HOME 'pslab' }
if ($Path -match '^~[\\/]pslab(?<rest>([\\/].*)?)$') {
$rest = $Matches.rest.TrimStart('\', '/')
if ($rest) { return (Join-Path $root $rest) } else { return $root }
}
$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
}
OpsKit.psm1 and OpsKit.psd1
# OpsKit.psm1 - loads Private helpers first, then Public commands, and exports only Public ones.
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop' # module scope only; callers are not affected
$private = @(Get-ChildItem -Path (Join-Path $PSScriptRoot 'Private') -Filter '*.ps1' -File)
$public = @(Get-ChildItem -Path (Join-Path $PSScriptRoot 'Public') -Filter '*.ps1' -File)
foreach ($file in $private + $public) {
. $file.FullName
}
Export-ModuleMember -Function $public.BaseName
@{
RootModule = 'OpsKit.psm1'
ModuleVersion = '0.3.0'
GUID = '4f6f2d8e-5b1c-4b8a-9a43-0c1d2e3f4a5b'
Author = 'pslab'
Description = 'OpsKit: operations helpers built during the PowerShell course.'
PowerShellVersion = '7.4'
CompatiblePSEditions = @('Core')
FunctionsToExport = @(
'Get-OpsConfig', 'Get-OpsServer', 'Test-OpsEndpoint', # v0.1 / v0.2
'Invoke-OpsRetry', 'Invoke-OpsBackup', 'Remove-OpsBackup' # new in v0.3
)
CmdletsToExport = @()
VariablesToExport = @()
AliasesToExport = @()
PrivateData = @{ PSData = @{ ReleaseNotes = '0.3.0: Invoke-OpsBackup, Remove-OpsBackup, Invoke-OpsRetry, JSON-lines log.' } }
}
The trap that motivated -ErrorAction Stop: a partial archive and $? = True
$fs = [IO.File]::Open((Resolve-Path ./data/access.log).Path, 'Open', 'Read', 'None') # simulate a log shipper Compress-Archive -LiteralPath (Get-ChildItem ./data -Force).FullName -DestinationPath ./tmp/locked2.zip "after (no -EA Stop): $? exists=$(Test-Path ./tmp/locked2.zip)" $fs.Dispose() Add-Type -AssemblyName System.IO.Compression.FileSystem $z = [IO.Compression.ZipFile]::OpenRead((Resolve-Path ./tmp/locked2.zip).Path) "entries: $($z.Entries.Count)"; ($z.Entries | Where-Object FullName -notlike 'files/*').FullName -join ', ' $z.Dispose()
Write-Error: The process cannot access the file 'C:\Users\labadmin\pslab\data\access.log' because it is being used by another process. after (no -EA Stop): True exists=True entries: 15 inventory.json, opskit.config.psd1, servers.csv
A complete archive has 16 entries (4 top-level files + 12 in files/, including [draft] notes.md and a&b;c.txt — -LiteralPath handled all odd names). Here access.log is missing, the zip exists and $? is True, because the error came from Write-Error inside the script-module function. With -ErrorAction Stop the same call raised System.IO.IOException (id CompressArchiveUnauthorizedAccessError,ZipArchiveHelper) and left no archive.
Preview, run, rerun
Import-Module ./OpsKit/OpsKit.psd1 -Force Invoke-OpsBackup -Timestamp '2026-11-24 10:00:00' -WhatIf | Format-Table Status, Items, Attempts, Removed -AutoSize Test-Path ./backups/pslab-data-20261124-100000.zip # then: Invoke-OpsBackup -Timestamp '2026-11-24 10:00:00' -Verbose | Format-Table Status, Items, SizeKB, Attempts, Removed, RunId -AutoSize Invoke-OpsBackup -Timestamp '2026-11-24 10:00:00' | Format-Table Status, Items, SizeKB, Attempts, Removed -AutoSize
What if: Performing the operation "Create backup of C:\Users\labadmin\pslab\data (5 items)" on target "C:\Users\labadmin\pslab\backups\pslab-data-20261124-100000.zip". Status Items Attempts Removed ------ ----- -------- ------- WhatIf 5 0 0 False VERBOSE: Performing the operation "Create backup of C:\Users\labadmin\pslab\data (5 items)" on target "C:\Users\labadmin\pslab\backups\pslab-data-20261124-100000.zip". Status Items SizeKB Attempts Removed RunId ------ ----- ------ -------- ------- ----- Created 5 8.00 1 0 b3965fc4 WARNING: Backup already exists, nothing to do: C:\Users\labadmin\pslab\backups\pslab-data-20261124-100000.zip Status Items SizeKB Attempts Removed ------ ----- ------ -------- ------- Exists 5 0 0
Rotation with -WhatIf, then for real
# simulate eight earlier nightly runs (Nov 16 ... Nov 23); -Keep 30 so nothing is rotated yet
16..23 | ForEach-Object { $null = Invoke-OpsBackup -Timestamp ([datetime]"2026-11-$_ 02:00:00") -Keep 30 }
(Get-ChildItem ./backups -Filter *.zip).Count
Invoke-OpsBackup -Timestamp '2026-11-25 02:00:00' -WhatIf | Format-Table Status, Removed -AutoSize
Invoke-OpsBackup -Timestamp '2026-11-25 02:00:00' | Format-Table Status, Items, SizeKB, Attempts, Removed -AutoSize
(Get-ChildItem ./backups -Filter *.zip).Name
9 What if: Performing the operation "Create backup of C:\Users\labadmin\pslab\data (5 items)" on target "C:\Users\labadmin\pslab\backups\pslab-data-20261125-020000.zip". What if: Performing the operation "Remove old backup" on target "pslab-data-20261117-020000.zip". What if: Performing the operation "Remove old backup" on target "pslab-data-20261116-020000.zip". Status Removed ------ ------- WhatIf 0 Status Items SizeKB Attempts Removed ------ ----- ------ -------- ------- Created 5 8.00 1 3 pslab-data-20261119-020000.zip pslab-data-20261120-020000.zip pslab-data-20261121-020000.zip pslab-data-20261122-020000.zip pslab-data-20261123-020000.zip pslab-data-20261124-100000.zip pslab-data-20261125-020000.zip
The preview named two deletions; the real run removed three (the 16th, 17th and 18th), because the new archive counted towards the seven. That is the documented preview limitation.
A locked file: retried, then success
# Hold an exclusive lock on access.log for 1.2 seconds in a background thread (simulates a log shipper)
$logFile = Join-Path $PWD 'data/access.log'
$lock = Start-ThreadJob {
$fs = [System.IO.File]::Open($using:logFile, 'Open', 'Read', 'None')
Start-Sleep -Milliseconds 1200; $fs.Dispose()
}
Start-Sleep -Milliseconds 200
Invoke-OpsBackup -Timestamp '2026-11-26 02:00:00' -MaxAttempts 4 -Verbose |
Format-Table Status, Attempts, Removed -AutoSize
$lock | Wait-Job | Remove-Job
VERBOSE: Performing the operation "Create backup of C:\Users\labadmin\pslab\data (5 items)" on target "C:\Users\labadmin\pslab\backups\pslab-data-20261126-020000.zip". VERBOSE: attempt 1/4 failed (IOException); retrying in 341 ms VERBOSE: attempt 2/4 failed (IOException); retrying in 809 ms Status Attempts Removed ------ -------- ------- Created 3 1
The log of that run
{"ts":"2026-11-25T02:03:12.361Z","level":"info","event":"backup.started","runId":"3214c421","archive":"C:\\Users\\labadmin\\pslab\\backups\\pslab-data-20261126-020000.zip","items":5,"source":"C:\\Users\\labadmin\\pslab\\data"}
{"ts":"2026-11-25T02:03:12.817Z","level":"warning","event":"backup.retry","runId":"3214c421","attempt":1,"delayMs":325,"error":"The process cannot access the file 'C:\\Users\\labadmin\\pslab\\data\\access.log' because it is being used by another process."}
{"ts":"2026-11-25T02:03:13.195Z","level":"warning","event":"backup.retry","runId":"3214c421","attempt":2,"delayMs":982,"error":"The process cannot access the file 'C:\\Users\\labadmin\\pslab\\data\\access.log' because it is being used by another process."}
{"ts":"2026-11-25T02:03:14.244Z","level":"info","event":"backup.created","runId":"3214c421","archive":"C:\\Users\\labadmin\\pslab\\backups\\pslab-data-20261126-020000.zip","attempts":3,"sizeKB":8.0}
Timestamps are UTC (02:03 UTC = the evening of 24 November in the lab's time zone), independent of the -Timestamp used for the archive name.
Locked for the whole run: retries exhausted
$fs = [System.IO.File]::Open("$PWD/data/access.log", 'Open', 'Read', 'None') # never released during the run
try {
Invoke-OpsBackup -Timestamp '2026-11-27 02:00:00' -BaseDelayMs 200
}
catch {
"caught: $($_.FullyQualifiedErrorId)"
"type: $($_.Exception.GetType().FullName)"
}
finally { $fs.Dispose() }
Test-Path ./backups/pslab-data-20261127-020000.zip
Get-Content ./backups/opskit-backup.jsonl | ConvertFrom-Json | Where-Object level -ne 'info' |
Select-Object -Last 3 | Format-Table level, event, attempt, delayMs, reason -AutoSize
caught: CompressArchiveUnauthorizedAccessError,Invoke-OpsBackup type: System.IO.IOException False level event attempt delayMs reason ----- ----- ------- ------- ------ warning backup.retry 1 168 warning backup.retry 2 279 error backup.failed CompressArchiveUnauthorizedAccessError,Invoke-OpsRetry
The original exception type survived two re-raises (Invoke-OpsRetry and Invoke-OpsBackup both use ThrowTerminatingError($_)), so callers can still catch [System.IO.IOException]. No partial archive was left.
Statement-terminating for the caller
Invoke-OpsBackup -Source ./nope; 'same line: not reached?'
'next statement'
try { Invoke-OpsBackup -Source ./nope } catch { "caught: $($_.FullyQualifiedErrorId)" }
Invoke-OpsBackup: Backup source not found: ./nope same line: not reached? next statement caught: OpsKit.BackupSourceNotFound,Invoke-OpsBackup
The nightly wrapper (scripts/Invoke-NightlyBackup.ps1)
<#
.SYNOPSIS
Nightly entry point: backs up ~/pslab/data with OpsKit and verifies the archive.
.DESCRIPTION
Exit codes: 0 success (or nothing to do); 1 backup failed; 2 configuration missing;
3 source folder missing; 4 archive failed verification.
.EXAMPLE
pwsh -NoProfile -NonInteractive -File ./scripts/Invoke-NightlyBackup.ps1 -WhatIf
#>
#Requires -Version 7.4
[CmdletBinding(SupportsShouldProcess)]
param(
[datetime]$Timestamp = (Get-Date),
[string]$Source,
[ValidateRange(1, 10)][int]$MaxAttempts = 3,
[ValidateRange(0, 60000)][int]$BaseDelayMs = 500
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop' # every error at this boundary is terminating
$PSNativeCommandUseErrorActionPreference = $true # and so is a native non-zero exit code
try {
Import-Module (Join-Path $PSScriptRoot '..' 'OpsKit' 'OpsKit.psd1') -Force
$backup = @{ Timestamp = $Timestamp; MaxAttempts = $MaxAttempts; BaseDelayMs = $BaseDelayMs }
if ($Source) { $backup.Source = $Source }
# Pass -WhatIf explicitly: a preference variable in this script's scope does not reliably
# reach functions in another module (it only does when this script runs in the global scope).
$backup.WhatIf = [bool]$WhatIfPreference
$result = Invoke-OpsBackup @backup
if ($result.Status -in 'Created', 'Exists') {
# Trust, but verify: open the archive and count its entries.
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip = $null
try {
$zip = [System.IO.Compression.ZipFile]::OpenRead($result.Archive)
$entries = $zip.Entries.Count
}
catch {
$err = [System.Management.Automation.ErrorRecord]::new($_.Exception.GetBaseException(),
'OpsKit.ArchiveInvalid', 'InvalidData', $result.Archive)
throw $err
}
finally { if ($zip) { $zip.Dispose() } }
Write-Information "verified $entries entries in $(Split-Path $result.Archive -Leaf)" -InformationAction Continue
}
$result
exit 0
}
catch {
$code = switch -Wildcard ($_.FullyQualifiedErrorId) {
'OpsKit.ConfigNotFound*' { 2 }
'OpsKit.BackupSourceNotFound*' { 3 }
'OpsKit.ArchiveInvalid*' { 4 }
default { 1 }
}
# One greppable line on stderr for the scheduler / CI log, then a meaningful exit code.
[Console]::Error.WriteLine("Invoke-NightlyBackup: exit $code [$($_.FullyQualifiedErrorId)] $($_.Exception.Message)")
exit $code
}
# a naive wrapper for comparison: scripts/Naive-Nightly.ps1 Import-Module (Join-Path $PSScriptRoot '..' 'OpsKit' 'OpsKit.psd1') -Force Invoke-OpsBackup -Source ./nope 'Backup finished'
pwsh -NoProfile -NonInteractive -File ./scripts/Naive-Nightly.ps1; "exit=$LASTEXITCODE" pwsh -NoProfile -NonInteractive -File ./scripts/Invoke-NightlyBackup.ps1 -Source ./nope; "exit=$LASTEXITCODE" pwsh -NoProfile -NonInteractive -File ./scripts/Invoke-NightlyBackup.ps1 -Timestamp '2026-11-28 02:00' -WhatIf | Out-Null; "exit=$LASTEXITCODE"
Invoke-OpsBackup: C:\Users\labadmin\pslab\scripts\Naive-Nightly.ps1:2
Line |
2 | Invoke-OpsBackup -Source ./nope
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Backup source not found: ./nope
Backup finished
exit=0
Invoke-NightlyBackup: exit 3 [OpsKit.BackupSourceNotFound,Invoke-OpsBackup] Backup source not found: ./nope
exit=3
What if: Performing the operation "Create backup of C:\Users\labadmin\pslab\data (5 items)" on target "C:\Users\labadmin\pslab\backups\pslab-data-20261128-020000.zip".
exit=0
The naive wrapper printed the error and “Backup finished”, and the scheduler saw exit 0. The hardened wrapper returned 3. The -WhatIf run exited 0 and created nothing (its “What if” line went into Out-Null with the rest of the child's output).
Invoke-NightlyBackup.ps1 did not pass -WhatIf to Invoke-OpsBackup; it relied on $WhatIfPreference. Under pwsh -File that worked, because a -File script runs in the global scope, which module functions can see. Called with & ./scripts/Invoke-NightlyBackup.ps1 -WhatIf it runs in a child scope, and the module function never saw the preference:
verified 16 entries in pslab-data-20261129-030000.zip old wrapper called with & -WhatIf, archive created: TrueA “dry run” created an archive — and rotation deleted the oldest real one. The fix is the explicit
$backup.WhatIf = [bool]$WhatIfPreference line; after it, the same call printed only the “What if” line and created nothing. Rule: pass -WhatIf/-Confirm explicitly across module boundaries.Goal: Install OpsKit v0.3 files, back up, rotate, survive a locked file and read the log. Environment: ~/pslab, PowerShell 7.4+. Cost: about 100 KB of archives in ~/pslab/backups.
Invoke-OpsRetry.ps1, Write-OpsLog.ps1 from Module 7) and import: Import-Module ./OpsKit/OpsKit.psd1 -Force; (Get-Module OpsKit).Version → 0.3.0.-Timestamp '2026-11-24 10:00:00': expect statuses WhatIf, Created, Exists (Commands tab).-Keep 30, preview with -WhatIf, run for real, and count: 7 archives remain. Explain the difference between the preview (2) and the real run (3).Get-Content ./backups/opskit-backup.jsonl | ConvertFrom-Json | Group-Object event -NoElement | Sort-Object Name | Format-Table Count, Name -AutoSize
Count Name
----- ----
11 backup.created
3 backup.failed
4 backup.removed
4 backup.retry
12 backup.started-Source ./nope and compare $LASTEXITCODE (0 vs 3).Remove-OpsBackup -Keep 1 -WhatIf to see what a strict rotation would delete; when finished with the lesson, Remove-Item ./backups -Recurse -Force.Case 1: nightly backups that were never complete
Problem: A restore test found that every archive for three months lacked the application's active log file. Root cause: the file was locked by the logging agent at 02:00; Compress-Archive wrote a non-terminating error, produced a partial zip, and the job's exit code was 0 — exactly the reproduction in the Commands tab. Fix: -ErrorAction Stop, retry with backoff on IOException, delete partial archives, verify entry counts, alert on non-zero exit. For files that are always locked, use a snapshot (VSS, LVM) or the application's own export instead of retrying.
Case 2: rotation deleted the only good backups
Problem: After a week of failed runs that each produced a tiny broken archive, rotation kept the seven broken ones and deleted the last good archive. Root cause: rotation counted files, not good backups, and failures left files behind. Fix: failed runs leave nothing (OpsKit deletes partial archives); rotation runs only after a successful, verified backup (a good extension: skip Remove-OpsBackup when status is not Created); alert when the newest good archive is older than 26 hours.
Case 3: the dry-run that wasn't
Problem: During a change review, Invoke-Backup -WhatIf (a predecessor of OpsKit's command) created a 2 GB archive on a nearly full disk. Root cause: the function relied on -WhatIf propagating into Compress-Archive. Fix: its own ShouldProcess around the write — and a test that runs every changing command with -WhatIf and asserts the file system is unchanged (integrated lab, scenario 3).
Common errors and fixes
Invoke-OpsBackup: Backup source not found
$env:OPSKIT_HOME; Test-Path ~/pslab/data; (Get-OpsConfig).Backup
Cause: wrong -Source, data not generated, or $env:OPSKIT_HOME still pointing at a test sandbox. Fix: regenerate data or clear the variable.
WARNING: Backup already exists, nothing to do
Cause: same timestamp (to the second) as an existing archive. Fix: intended idempotency; omit -Timestamp in production.
The process cannot access the file … being used by another process (after all retries)
Fix: find the holder (Get-Process / Resource Monitor / lsof on Linux), raise -MaxAttempts/-BaseDelayMs if the lock is short, or exclude the file with Backup.Exclude if it is always open.
OpsKit config not found
Fix: Get-OpsConfig -Path … to test a path; check $env:OPSKIT_HOME; regenerate with New-LabData.ps1.
For “the error was not caught” and “the script reported success but failed”, use the interactive tree in the Animation tab.
1. List the runs of the last day that failed, with their reason.
Get-Content ~/pslab/backups/opskit-backup.jsonl | ConvertFrom-Json |
Where-Object { $_.event -eq 'backup.failed' -and $_.ts -gt (Get-Date).AddDays(-1) } |
Select-Object ts, runId, reason2. Keep only the three newest archives, after previewing.
Remove-OpsBackup -Keep 3 -WhatIf Remove-OpsBackup -Keep 3
Operations ask you to make the nightly job “never fail” because the alerts are noisy: a locked file causes one failed night per week. What do you change, and what do you refuse to change?
Change: tune retries for the observed lock duration (more attempts or a longer base delay), exclude files that are always open or back them up through a snapshot, and alert only when there is no successful backup within 26 hours rather than on every failed attempt. Refuse: swallowing errors or returning exit 0 on failure — a silent failure is how teams discover missing backups during a restore. Keep the exit code honest and the log complete; make the alerting smarter.
Verified teaching videos
No verified video covers this OpsKit design; these verified videos cover the building blocks it combines.
Official documentation
Video storyboard (about 90 seconds)
Visual: a zip with 15 of 16 files and a green check mark that turns red when the missing access.log is highlighted.
Narration: a backup that reports success but is incomplete is worse than a failure.
Visual: the Invoke-OpsBackup flowchart lighting up: guard, exists?, ShouldProcess, retry loop with a partial zip being deleted.
Narration: guard, preview, retry, clean up.
Visual: a row of nine archives; -WhatIf greys out two, the real run removes three.
Narration: rotation inherits WhatIf — and a preview is only as honest as your code.
Visual: a scheduler dashboard showing exit codes 0, 1, 3 with matching JSON events.
Narration: exit codes for machines, JSON lines for people who investigate.
Command cheat sheet
1. Error model
$Error[0]; $Error.Count; $Error.Clear(); $? $e = $Error[0] $e.Exception.GetType().FullName; $e.FullyQualifiedErrorId $e.CategoryInfo; $e.TargetObject; $e.ScriptStackTrace Get-Error -Newest 1 # non-terminating → continue · statement-terminating → next statement # script-terminating (throw, Stop) → up to nearest try/catch
2. try / catch / finally
try { Get-Item $p -ErrorAction Stop }
catch [System.Management.Automation.ItemNotFoundException] { … }
catch [System.IO.IOException], [System.TimeoutException] { … }
catch { throw } # rethrow unchanged
finally { $fs.Dispose() }
$ErrorActionPreference = 'Stop' # script boundary
cmd -ErrorAction Ignore # local opt-out, not in $Error
cmd -ErrorVariable ev; cmd -ErrorVariable +ev3. Raising errors (advanced functions)
Write-Error 'one item failed' # non-terminating
$PSCmdlet.WriteError($record)
$PSCmdlet.ThrowTerminatingError($record) # statement-terminating
throw 'fatal' # script-terminating
[System.Management.Automation.ErrorRecord]::new(
[System.IO.FileNotFoundException]::new('msg'),
'OpsKit.ConfigNotFound', 'ObjectNotFound', $target)4. Native commands
git fetch; if ($LASTEXITCODE -ne 0) { throw "git: $LASTEXITCODE" }
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true # 7.4+, default $false
catch [System.Management.Automation.NativeCommandExitException] { $_.Exception.ExitCode }
& { $PSNativeCommandUseErrorActionPreference = $false; robocopy … }
if ($LASTEXITCODE -ge 8) { throw }
tool 2>$null · tool 2>&1 | % { "$_" } # stderr ≠ failure5. Streams
# 1 out · 2 error · 3 warning · 4 verbose · 5 debug · 6 information/Write-Host f 2>&1 · f 3> warn.txt · f *> all.txt · f 6>$null f -Verbose -InformationAction Continue f -ErrorVariable e -WarningVariable w -InformationVariable i $r = f 6>&1 # capture Write-Host Get-Variable *Preference
6. Strict mode and defence
Set-StrictMode -Version Latest
[ValidateRange(1, 365)][int]$Keep
[ValidateSet('dev','staging','prod')][string]$Env
[ValidateScript({ Test-Path -LiteralPath $_ }, ErrorMessage = 'Not found: {0}')]
if ($null -eq $x) { } # $null on the LEFT
@($items).Count; $h.ContainsKey('k'); $h['k']
$PSCmdlet.GetUnresolvedProviderPathFromPSPath($p) # before .NET calls7. Safe change
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
if ($PSCmdlet.ShouldProcess($target, 'Action')) { change }
f -WhatIf · f -Confirm · f -Confirm:$false
OtherModule\Cmd -WhatIf:$WhatIfPreference # cross-module: pass it!
Add-Content $log $line -WhatIf:$false # logs during -WhatIf
if (Test-Path $target) { return } # idempotent8. Retries, timeouts, logs, OpsKit
Invoke-OpsRetry -RetryOn ([System.IO.IOException]) -MaxAttempts 4 { … -ErrorAction Stop }
$j | Wait-Job -Timeout 5; $j | Stop-Job
Invoke-RestMethod $u -TimeoutSec 10
[ordered]@{ ts = …; level = 'info'; event = 'x' } | ConvertTo-Json -Compress -Depth 4
Invoke-OpsBackup -WhatIf; Invoke-OpsBackup -Verbose
Remove-OpsBackup -Keep 7 -WhatIf
pwsh -NoProfile -NonInteractive -File ./scripts/Invoke-NightlyBackup.ps1; $LASTEXITCODEIntegrated lab + final quiz
~/pslab/scripts/Test-OpsFailure.ps1: a failure-injection script that drives every error path of the nightly backup — success, idempotent rerun, -WhatIf, transient and persistent locks, missing source, corrupt archive, missing config — and checks exit codes, archives and log events in a sandboxScenario
Before OpsKit v0.3 goes onto the team's servers, you must prove that the nightly job tells the truth: every failure produces a non-zero, distinct exit code and a log event; nothing is left half-done; and -WhatIf changes nothing. You will not test this against real backups. The script builds a sandbox in ~/pslab/tmp/fi, points $env:OPSKIT_HOME at it, runs Invoke-NightlyBackup.ps1 (Module 8) as a separate process — exactly as a scheduler would — eight times with injected faults, and checks the results.
~/pslab/scripts/Test-OpsFailure.ps1:
<#
.SYNOPSIS
Failure injection for Invoke-NightlyBackup.ps1: drives every error path and checks
exit codes, archives and the JSON-lines log.
.DESCRIPTION
Works in a throw-away OpsKit root (~/pslab/tmp/fi) via $env:OPSKIT_HOME, so real
backups are never touched. Exit code: 0 all scenarios passed, 1 otherwise.
#>
#Requires -Version 7.4
[CmdletBinding()]
param([string]$Root = (Join-Path $PSScriptRoot '..' 'tmp' 'fi'))
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$Root = [System.IO.Path]::GetFullPath($Root)
$nightly = Join-Path $PSScriptRoot 'Invoke-NightlyBackup.ps1'
$data = Join-Path $Root 'data'
$backups = Join-Path $Root 'backups'
$logFile = Join-Path $backups 'opskit-backup.jsonl'
# Fresh sandbox: a copy of the dataset, no backups yet.
if (Test-Path -LiteralPath $Root) { Remove-Item -LiteralPath $Root -Recurse -Force }
$null = New-Item -ItemType Directory -Path $Root
Copy-Item -LiteralPath (Join-Path $PSScriptRoot '..' 'data') -Destination $data -Recurse
$env:OPSKIT_HOME = $Root # inherited by every child pwsh
function Invoke-Scenario {
param([string]$Name, [int]$ExpectExit, [string[]]$Arguments = @(), [string]$ExpectEvent, [scriptblock]$Check = { $true })
$before = if (Test-Path -LiteralPath $logFile) { @(Get-Content -LiteralPath $logFile).Count } else { 0 }
$stderr = Join-Path $Root 'stderr.txt'
$null = pwsh -NoProfile -NonInteractive -File $nightly @Arguments 2> $stderr
$exit = $LASTEXITCODE
$events = @(if (Test-Path -LiteralPath $logFile) {
Get-Content -LiteralPath $logFile | Select-Object -Skip $before | ConvertFrom-Json | ForEach-Object event
})
$eventOk = -not $ExpectEvent -or $events -contains $ExpectEvent
[pscustomobject]@{
Scenario = $Name
Expected = $ExpectExit
Exit = $exit
Events = ($events | Group-Object -NoElement | ForEach-Object { '{0}x{1}' -f $_.Count, ($_.Name -replace '^backup\.') }) -join ' '
Passed = ($exit -eq $ExpectExit) -and $eventOk -and [bool](& $Check)
Stderr = (Get-Content -LiteralPath $stderr -Raw -ErrorAction Ignore) -replace '\s+$'
}
}
function Lock-File([string]$Path, [int]$Milliseconds) {
Start-ThreadJob -ArgumentList $Path, $Milliseconds {
param($p, $ms)
$fs = [System.IO.File]::Open($p, 'Open', 'Read', 'None')
try { Start-Sleep -Milliseconds $ms } finally { $fs.Dispose() } # Stop-Job must release the lock too
}
Start-Sleep -Milliseconds 300 # make sure the lock is taken before the child starts
}
$zipFor = { param($ts) Join-Path $backups ('pslab-data-{0:yyyyMMdd-HHmmss}.zip' -f [datetime]$ts) }
$results = [System.Collections.Generic.List[object]]::new()
# 1. Happy path
$results.Add((Invoke-Scenario 'happy path' 0 @('-Timestamp', '2026-11-24 01:00') 'backup.created' { Test-Path (& $zipFor '2026-11-24 01:00') }))
# 2. Same timestamp again: idempotent, nothing written
$results.Add((Invoke-Scenario 'rerun is idempotent' 0 @('-Timestamp', '2026-11-24 01:00') -Check { @(Get-ChildItem $backups -Filter *.zip).Count -eq 1 }))
# 3. -WhatIf: no archive may appear
$results.Add((Invoke-Scenario '-WhatIf changes nothing' 0 @('-Timestamp', '2026-11-24 02:00', '-WhatIf') -Check { -not (Test-Path (& $zipFor '2026-11-24 02:00')) }))
# 4. Transient lock (2.5 s): retried, then success
$job = Lock-File (Join-Path $data 'access.log') 2500
$results.Add((Invoke-Scenario 'transient lock is retried' 0 @('-Timestamp', '2026-11-24 03:00', '-MaxAttempts', '6') 'backup.retry'))
$job | Wait-Job | Remove-Job
# 5. Persistent lock (15 s): retries exhausted -> exit 1, no partial archive left
$job = Lock-File (Join-Path $data 'access.log') 15000
$results.Add((Invoke-Scenario 'persistent lock fails' 1 @('-Timestamp', '2026-11-24 04:00', '-BaseDelayMs', '200') 'backup.failed' { -not (Test-Path (& $zipFor '2026-11-24 04:00')) }))
$job | Stop-Job -PassThru | Remove-Job
# 6. Missing source folder -> exit 3
$results.Add((Invoke-Scenario 'missing source' 3 @('-Source', (Join-Path $Root 'nope')) 'backup.failed'))
# 7. Corrupt archive with the requested name -> verification fails -> exit 4
Set-Content -LiteralPath (& $zipFor '2026-11-24 05:00') -Value 'not a zip'
$results.Add((Invoke-Scenario 'corrupt archive detected' 4 @('-Timestamp', '2026-11-24 05:00')))
# 8. Missing configuration -> exit 2
Rename-Item -LiteralPath (Join-Path $data 'opskit.config.psd1') -NewName 'opskit.config.psd1.bak'
$results.Add((Invoke-Scenario 'missing config' 2 @('-Timestamp', '2026-11-24 06:00')))
Rename-Item -LiteralPath (Join-Path $data 'opskit.config.psd1.bak') -NewName 'opskit.config.psd1'
$results | Format-Table Scenario, Expected, Exit, Passed, Events -AutoSize | Out-Host
$results | Where-Object Stderr | ForEach-Object { "stderr [$($_.Scenario)]: $($_.Stderr)" } | Out-Host
$failed = @($results | Where-Object { -not $_.Passed })
if ($failed) { Write-Warning "$($failed.Count) scenario(s) failed: $($failed.Scenario -join ', ')"; exit 1 }
'All failure scenarios behaved as designed.'
exit 0
| # | Injected fault | Error path exercised | Expected exit / event |
|---|---|---|---|
| 1 | none | happy path | 0 / backup.created |
| 2 | same timestamp | idempotency (M6) | 0 / no event, still one archive |
| 3 | -WhatIf | ShouldProcess across a process and a module boundary (M6) | 0 / no archive |
| 4 | lock for 2.5 s | terminating IOException → retry (M2, M7) | 0 / backup.retry |
| 5 | lock for 15 s | retries exhausted, cleanup, typed rethrow (M7, M8) | 1 / backup.failed, no partial zip |
| 6 | missing source | guard clause, ThrowTerminatingError, id → exit code (M2, M5) | 3 / backup.failed |
| 7 | garbage file with the archive's name | verification of “Exists” (M8) | 4 |
| 8 | config renamed | error from a nested command reaches the boundary (M1) | 2 |
The child process is a native command from the harness's point of view (M3): its exit code arrives in $LASTEXITCODE, its stderr is redirected to a file (M4). The harness itself runs with strict mode and Stop (M5). The Lock-File helper disposes the file handle in finally — the first version did not, and Stop-Job left access.log locked for later scenarios (found while writing this lab).
Set-Location ~/pslab pwsh -NoProfile -NonInteractive -File ./scripts/Test-OpsFailure.ps1; "exit=$LASTEXITCODE"
Scenario Expected Exit Passed Events -------- -------- ---- ------ ------ happy path 0 0 True 1xcreated 1xstarted rerun is idempotent 0 0 True -WhatIf changes nothing 0 0 True transient lock is retried 0 0 True 1xcreated 3xretry 1xstarted persistent lock fails 1 1 True 1xfailed 2xretry 1xstarted missing source 3 3 True 1xfailed corrupt archive detected 4 4 True missing config 2 2 True stderr [persistent lock fails]: Invoke-NightlyBackup: exit 1 [CompressArchiveUnauthorizedAccessError,Invoke-OpsBackup] The process cannot access the file 'C:\Users\labadmin\pslab\tmp\fi\data\access.log' because it is being used by another process. stderr [missing source]: Invoke-NightlyBackup: exit 3 [OpsKit.BackupSourceNotFound,Invoke-OpsBackup] Backup source not found: C:\Users\labadmin\pslab\tmp\fi\nope stderr [corrupt archive detected]: Invoke-NightlyBackup: exit 4 [OpsKit.ArchiveInvalid] The parameter is incorrect. : 'C:\Users\labadmin\pslab\tmp\fi\backups\pslab-data-20261124-050000.zip'. stderr [missing config]: Invoke-NightlyBackup: exit 2 [OpsKit.ConfigNotFound,Get-OpsConfig] OpsKit config not found: C:\Users\labadmin\pslab\tmp\fi\data\opskit.config.psd1 All failure scenarios behaved as designed. exit=0
The whole run takes about 12 seconds. “The parameter is incorrect” is the base exception ZipFile.OpenRead produced on Windows for a 11-byte text file; the id OpsKit.ArchiveInvalid is what the wrapper maps to exit 4.
Invoke-OpsBackup.ps1 by changing if (Test-Path -LiteralPath $zip) { to if ($false) {, re-run, then restore the line:
Scenario Expected Exit Passed Events -------- -------- ---- ------ ------ happy path 0 0 True 1xcreated 1xstarted rerun is idempotent 0 0 True 1xcreated 1xretry 1xstarted -WhatIf changes nothing 0 0 True transient lock is retried 0 0 True 1xcreated 2xretry 1xstarted persistent lock fails 1 1 True 1xfailed 2xretry 1xstarted missing source 3 3 True 1xfailed corrupt archive detected 4 0 False 1xcreated 1xretry 1xstarted missing config 2 2 True … WARNING: 1 scenario(s) failed: corrupt archive detected exit=1
Read the events: without the existence check, Compress-Archive failed because the destination existed, the retry hook deleted the existing archive as if it were a partial one, and the next attempt replaced it. In scenario 2 that silently overwrote a good backup (the check still passed — one archive); in scenario 7 the harness caught it: exit 0 instead of 4. Two lessons: order your guards before your cleanup logic, and assert on events as well as exit codes.
& … -WhatIf inside pwsh -Command (the case from Module 8's callout) and asserts no archive; and a scenario for a native failure in the wrapper (e.g. add a post-backup git -C $data status and run it outside a repository — what exit code does the wrapper return with $PSNativeCommandUseErrorActionPreference = $true?).Remove-Item ~/pslab/tmp/fi -Recurse -ForceOpen-ended self-check
1. Walk an IOException from Compress-Archive all the way to the scheduler's exit code.
Compress-Archive (with -ErrorAction Stop) raises the IOException as a script-terminating error inside Invoke-OpsRetry's try; catch checks the exception chain against -RetryOn, logs via -OnRetry, waits and retries; after the last attempt it calls ThrowTerminatingError($_); Invoke-OpsBackup's catch logs backup.failed, deletes any partial archive and calls ThrowTerminatingError($_) again; in the wrapper, the statement-terminating error is caught by the boundary try/catch, the id maps to 1, one line goes to stderr and exit 1 ends the pwsh -File process with code 1.
2. Why does the naive wrapper exit 0 although Invoke-OpsBackup “throws”?
It uses ThrowTerminatingError, which is statement-terminating: without try/catch or Stop the caller's next statement runs and the script ends normally (exit 0). Only a script-terminating error (or an explicit exit N) changes the -File exit code.
3. When is it right to swallow an error?
When it is expected and harmless, the decision is explicit and local, and something is recorded: Get-Command az -ErrorAction Ignore to test for a tool; Write-OpsLog turning a log failure into a warning so logging can't fail a backup. Never globally, never silently for changes.
4. Give two reasons a -WhatIf preview can differ from the real run, both seen in this lesson.
Code paths that don't see the preference (other script modules — Compress-Archive, the first wrapper via &); and logic that depends on the change itself (rotation counting the archive that would have been created: 2 vs 3 deletions).
Sources and version notes
| Topic | Verified result | Sources (accessed 2026-11-24) |
|---|---|---|
| Error kinds and $Error | Non-terminating, statement- and script-terminating behaviour reproduced with Show-ErrorKinds.ps1 (exit 1 from throw); SilentlyContinue records in $Error, Ignore does not; Get-Error output captured | Everything about exceptions; Get-Error; about_Automatic_Variables |
| try/catch, throw, ThrowTerminatingError, trap | Typed catch matches the original exception after -ErrorAction Stop; ThrowTerminatingError is statement-terminating for the caller, throw script-terminating; $ErrorActionPreference = 'SilentlyContinue' hides a conversion error; binding errors ignore -ErrorAction; a try block also catches statement-terminating errors (the wrapper still worked with Stop commented out) | about_Try_Catch_Finally; about_Throw; about_Trap; about_CommonParameters |
| Native commands | $PSNativeCommandUseErrorActionPreference defaults to False; with Stop it raises NativeCommandExitException (ProgramExitedWithNonZeroCode, .ExitCode); stderr does not set $? or trigger Stop; redirected stderr lines are ErrorRecords not added to $Error; robocopy exit 1 raised the exception; git 2.51.2 exits 129 / 128 | about_Preference_Variables; What's New in PowerShell 7.4; about_Redirection |
| Streams | Record types per stream; -InformationVariable collects records while the preference is SilentlyContinue; Write-Host has tag PSHOST; *> wrote the Write-Information line but no verbose/debug lines; nested -Verbose flows into advanced functions | about_Output_Streams; about_Redirection |
| Strict mode and defensive coding | Latest catches uninitialized variables, missing properties (including hashtable keys via dot notation), method-call syntax and out-of-range indexes; errors are statement-terminating; child scope can switch it off; $arr -eq $null filters | Set-StrictMode; Everything about $null; about_Functions_Advanced_Parameters |
| ShouldProcess | -WhatIf output format; compiled cmdlets and same-module functions inherit $WhatIfPreference; a function in another script module (test module, Compress-Archive 1.2.7) does not, unless the preference is set in the global scope; Add-Content is skipped under WhatIf; ShouldProcess prompt under -NonInteractive throws | Everything about ShouldProcess; about_Functions_CmdletBindingAttribute; How to request confirmations |
| Retries, timeouts, transcripts | Retry timings with seed 42; Wait-Job -Timeout leaves the job Running; cancellation token raises TaskCanceledException; -TimeoutSec 2 cancelled a slow local request after 2.0 s, -OperationTimeoutSeconds 2 did not (returned after 5.2 s); transcript omitted native console output; ConvertTo-Json depth warning | Invoke-RestMethod; Wait-Job; Start-Transcript |
| Compress-Archive | Microsoft.PowerShell.Archive 1.2.7 (script module): a locked file without Stop → non-terminating Write-Error, $? = True, 15-entry partial archive; with Stop → IOException, id CompressArchiveUnauthorizedAccessError,ZipArchiveHelper, no archive; -LiteralPath archived all 12 odd file names | Compress-Archive |
| OpsKit v0.3 | All Module 8 runs and the 8-scenario failure-injection harness (12 s) on 7.6.10; three bugs found while writing and fixed: relative log path in Write-OpsLog, wrapper relying on $WhatIfPreference across a module boundary, harness lock not released by Stop-Job | Actual runs for this lesson |
Video verification notes
Only videos whose titles and channels were confirmed via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-24 are listed:
- PowerShell Quick Tips : Errors — JackedProgrammer (Module 1)
- PowerShell Errors and Exceptions Handling — TechThoughts (Module 1)
- PowerShell 7 Tutorials for Beginners #10 : Error Handling (Try Catch Finally) — JackedProgrammer (Module 2)
- How to Handle Errors in PowerShell | Try, Catch, and Finally — Cloud360 Training (Module 2)
- 🔴Error Handling in PowerShell — PDQ (Module 2)
- Intro To Error Handling in PowerShell — ed wilson (Module 8)
- Complete PowerShell Error Handling Guide — NinjaOne IT Tech Tips (Modules 3, 5)
- Use PowerShell WhatIf So You Don't Break Stuff — Jeff Brown Tech (Module 6)
- Powershell Confirm, Impact and What-if — Tips For IT Pros (Module 6)
- PowerShell ShouldProcess: Build WhatIf Into Your Own Scripts — AISLabs AI (Module 6)
- PowerShell WhatIf and Confirm: Dry-Run Before You Delete — AISLabs AI (Module 8)
- PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training (Module 4)
oEmbed verifies titles and channels only; the videos were not watched segment by segment, and the descriptions come from titles and search snippets. Many use Windows PowerShell 5.1, where native stderr handling differs (Module 3). No verified video was found for $PSNativeCommandUseErrorActionPreference, the six streams in 7.x, Set-StrictMode, cross-module -WhatIf propagation, or retry/backoff and JSON-lines logging; this lesson's runs and the documentation are the reference.
Voice narration notes
The “Voice” tab uses the browser's built-in Web Speech API (en-US); it needs no network access. The courseware cannot embed MP3 files or generate video; narration scripts and storyboards can be passed to a TTS or video tool.
Known limitations
- Run environment: all “Actual output (7.6.10)” blocks come from Windows 11 with PowerShell 7.6.10; paths were replaced with
C:\Users\labadmin\pslab\…, and OpsKit's root was pointed at the lab folder with$env:OPSKIT_HOME. Interactive-looking snippets were run non-interactively through a small host script that executes each top-level statement like typed input (pwsh -NonInteractive); a script-terminating error therefore ended the rest of a snippet, which matches script behaviour. - Not run on Linux or macOS:
sh -c 'exit 3',rsyncand file-locking behaviour on Unix (advisory locks:FileShare.Nonedoes not block other processes there the same way) are described from documentation. The locked-file retry scenarios are Windows-specific as written. - Values that depend on timing or randomness (retry delays, number of retries in scenarios 4/5, RunIds, timestamps) differ on every run; the seeded
Invoke-OpsRetryexample (seed 42) is reproducible. - “Expected output” blocks: the Linux/macOS commands and the Windows-PowerShell-5.1 comparisons were not run. The exact base exception for opening a non-zip file (“The parameter is incorrect”) is platform-dependent.
- The rotation preview under-reports deletions by one (by design of this teaching version); the animations simplify engine internals (exact exception types used for propagation, host prompt flow).