Skip to content

Lesson 4 of 13 · 13m

Errors Are Objects Too

ErrorRecords travel a separate stream, try/catch only sees terminating errors, and native commands report through $LASTEXITCODE.

Red text on your console is not "an error happened." It is an ErrorRecord object — exception, category, target object, fully qualified error ID, invocation info — pushed onto the error stream (stream 2), which sits beside the output stream (stream 1) like a second pipeline. When you see red, a typed object went somewhere you weren't looking.

Six streams, not one console

PowerShell 5 and later route host chatter through streams: 1 Success (output), 2 Error, 3 Warning, 4 Verbose, 5 Debug, 6 Information. Redirection works per stream: 4>verbose.log captures Verbose, *>everything.log merges all six. Write-Host writes to stream 6 in modern PowerShell — capturable — but in Windows PowerShell 4 and earlier it bypassed everything and went straight to the console. If your automation depends on Write-Host output being logged, it wasn't, for years, and nobody noticed.

Write-Verbose and Write-Debug stay silent unless -Verbose/-Debug or the corresponding $VerbosePreference/$DebugPreference asks for them — that's what makes them the correct channels for automation chatter. They cost nothing when off.

Terminating vs non-terminating

Here is the distinction that breaks everyone's first try/catch. Get-Item missing.txt produces a non-terminating error: an ErrorRecord on stream 2, and the pipeline continues. throw "boom" produces a terminating error: execution stops. try/catch catches only terminating errors.

try {
    Get-Item missing.txt        # non-terminating — catch never sees it
} catch {
    "caught"                    # never runs
}

The fix is -ErrorAction Stop on the call, which promotes that call's non-terminating errors to terminating: try { Get-Item missing.txt -ErrorAction Stop } catch { ... }. This is a per-command decision, which is correct — a Get-Item miss in a loop over ten thousand paths should be non-terminating; a miss for your config file should kill the script.

$ErrorActionPreference = 'Stop' at the top of a script promotes every non-terminating error everywhere — including ones cmdlet authors intentionally made non-terminating, like Remove-Item on a file that vanished mid-run. Some people set it globally as a discipline hack; what they get is a script that dies on warnings-as-errors semantics nobody designed for. Prefer -ErrorAction at the call site.

$Error is a collection

$Error holds the recent ErrorRecords (default max 256, $MaximumErrorCount), newest first. $Error[0].Exception is the real exception — .GetType().FullName, .Message, .InnerException, .StackTrace. .InvocationInfo tells you the line and command that threw. .FullyQualifiedErrorId is the stable string to switch on ('PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand') — far better than regexing message text, which is localized. $? is the boolean "last command succeeded" — useful, but it's a statement-level truth, not a per-item one.

-ErrorVariable myErr captures a call's non-terminating errors into a named variable — Get-ChildItem -Recurse -ErrorVariable skipped -ErrorAction SilentlyContinue collects every access-denied into $skipped for your report while the loop keeps moving.

There's a third failure class that isn't an ErrorRecord at all: a .NET exception thrown from a method call. [System.IO.File]::ReadAllText('missing') throws FileNotFoundException straight into catch — method calls don't get -ErrorAction; they're always terminating. That's why the same script treats Get-Item misses (non-terminating, ignorable) and ::ReadAllText misses (terminating, caught) differently, and why auditing a script means checking which API each failure actually uses.

Native commands aren't cmdlets

robocopy, net.exe, git, ssh don't write ErrorRecords. They set $LASTEXITCODE, and non-zero exit does not raise a PowerShell error — your try/catch sees nothing. Check $LASTEXITCODE explicitly, or on PowerShell 7.4+ set $PSNativeCommandUseErrorActionPreference = $true to make non-zero exits respect -ErrorAction. And mind robocopy's exit codes: 0-7 are success tiers (0 = nothing copied, 1 = files copied, 3 = files+extras), 8+ are failures. Treating non-zero as failure means your sync script pages you every time it actually worked.

The practice

Automation errors must end up somewhere a human sees them. Decide per call: -ErrorAction Stop inside try/catch for things that must abort, -ErrorVariable for things you collect and report, -ErrorAction SilentlyContinue only when a miss is a valid answer. At script end, exit $code so Task Scheduler's LastTaskResult means something. And keep $ErrorActionPreference on Continue — promote errors where you handle them, not globally.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.