Error Handling
How PowerShell errors really work, from terminating and non-terminating errors to try/catch/finally and native exit codes, plus a robust pattern for scripts that run unattended.
By The Dark DebuggerUpdated 29 min read
This article explains how PowerShell reports failures and how to handle them deliberately:
the two kinds of errors, -ErrorAction and $ErrorActionPreference, try/catch/finally,
the error record, throw versus Write-Error, exit codes from native programs, strict mode,
and logging. It ends with a script template you can use for anything that runs unattended.
It assumes you can write functions and
scripts.
Why this matters: the backup that deleted the data
Here is a "backup" script that someone wanted to keep quiet, so they set the error
preference to SilentlyContinue. The backups folder doesn't exist:
$ErrorActionPreference = 'SilentlyContinue'
$source = './data/orders.csv'
Copy-Item -Path $source -Destination ./backups/orders.csv
Remove-Item -Path $source
"Backup done. Source still exists: $(Test-Path -Path $source); backup exists: $(Test-Path -Path ./backups/orders.csv)"Backup done. Source still exists: False; backup exists: FalseThe copy failed silently, the delete succeeded, and the script reported success. The data is gone. Nothing here is exotic. It's the default PowerShell behaviour of carrying on after an error, made invisible. Most PowerShell error-handling bugs come from not knowing which errors stop a script and which don't, so that's where we start.
Every example was run with pwsh -NoProfile -File on PowerShell 7.6.9 (Linux), so error
messages show the script path and line. A few Windows PowerShell 5.1 differences, marked as
such, were checked on Windows 11.
Terminating and non-terminating errors
A non-terminating error reports a problem with one item and lets the command carry on with the rest. Most cmdlet errors are like this, because a cmdlet usually processes many items:
$paths = './config/app.json', './config/missing.json', './config/db.json'
Get-Item -Path $paths | Select-Object -Property Name, Length
'Script kept going.'Name Length
---- ------
app.json 41
Get-Item: /home/sid/errors/nonterminating.ps1:2
Line |
2 | Get-Item -Path $paths | Select-Object -Property Name, Length
| ~~~~~~~~~~~~~~~~~~~~~
| Cannot find path
| '/home/sid/errors/config/missing.json' because it
| does not exist.
db.json 42
Script kept going.One bad path didn't stop Get-Item from returning the other two. That is often exactly
right. The problem is that try/catch only catches terminating errors:
try {
Get-Item -Path ./config/missing.json
'This line still runs'
}
catch {
'Caught it'
}Get-Item: /home/sid/errors/try-nonterminating.ps1:2
Line |
2 | Get-Item -Path ./config/missing.json
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot find path
| '/home/sid/errors/config/missing.json' because it
| does not exist.
This line still runsThe catch block never ran. To make a cmdlet's error catchable, turn it into a terminating
error with -ErrorAction Stop:
try {
Get-Item -Path ./config/missing.json -ErrorAction Stop
'This line is skipped'
}
catch {
"Caught: $($_.Exception.Message)"
}Caught: Cannot find path '/home/sid/errors/config/missing.json' because it does not exist.Terminating errors themselves come in two strengths, and the difference shows when there's
no try around them:
$divisor = 0
$result = 10 / $divisor
'after the division error'
[int]::Parse('abc')
'after the .NET method error'
throw 'deployment aborted'
'after throw'RuntimeException: /home/sid/errors/three-kinds.ps1:2
Line |
2 | $result = 10 / $divisor
| ~~~~~~~~~~~~~~~~~~~~~~~
| Attempted to divide by zero.
after the division error
MethodInvocationException: /home/sid/errors/three-kinds.ps1:5
Line |
5 | [int]::Parse('abc')
| ~~~~~~~~~~~~~~~~~~~
| Exception calling "Parse" with "1" argument(s): "The input string 'abc'
| was not in a correct format."
after the .NET method error
Exception: /home/sid/errors/three-kinds.ps1:8
Line |
8 | throw 'deployment aborted'
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
| deployment abortedThe script exited with code 1 after the throw.
| Kind | Examples | Without try/catch | Caught by try/catch? |
|---|---|---|---|
| Non-terminating | Most cmdlet errors: missing path, access denied on one file | Error shown, command and script continue | No, unless -ErrorAction Stop |
| Statement-terminating | .NET method exceptions, runtime errors, $PSCmdlet.ThrowTerminatingError() | The failing statement stops, the script continues | Yes |
| Script-terminating | throw, any error under -ErrorAction Stop | The whole script stops (exit code 1) | Yes |
The middle row surprises people. A failed .NET call doesn't stop your script unless you
catch it or set $ErrorActionPreference = 'Stop'.
-ErrorAction and $ErrorActionPreference
-ErrorAction (alias -EA) is a common parameter on every cmdlet and advanced function.
It sets what a non-terminating error does for that one call. $ErrorActionPreference sets
the default for everything in the current scope.
| Value | Shows the error | Added to $Error | Continues |
|---|---|---|---|
Continue (default) | Yes | Yes | Yes |
SilentlyContinue | No | Yes | Yes |
Ignore | No | No | Yes |
Stop | — | Yes | No: becomes a terminating error you can catch |
Inquire | Asks the user what to do | Yes | Depends on the answer |
Break (7.0+) | Enters the debugger | Yes | Debugger |
The difference between SilentlyContinue and Ignore is whether the error is recorded:
$Error.Clear()
Get-Item -Path ./nope1 -ErrorAction SilentlyContinue
"SilentlyContinue: nothing shown, `$Error.Count = $($Error.Count)"
Get-Item -Path ./nope2 -ErrorAction Ignore
"Ignore: nothing shown, `$Error.Count = $($Error.Count)"
$item = Get-Item -Path ./nope3 -ErrorAction SilentlyContinue
"Result is null: $($null -eq $item)"SilentlyContinue: nothing shown, $Error.Count = 1
Ignore: nothing shown, $Error.Count = 1
Result is null: TrueSilentlyContinue with a $null check is the right tool for "maybe it exists". Use
Test-Path when you can. Setting the preference to Stop at the top of a script makes
every cmdlet error catchable without repeating -ErrorAction Stop. An explicit parameter
still wins for one call:
$ErrorActionPreference = 'Stop'
try {
Get-Item -Path ./config/missing.json
'not reached'
}
catch {
"Caught without -ErrorAction: $($_.Exception.Message)"
}
Get-Item -Path ./config/missing.json -ErrorAction SilentlyContinue
'An explicit -ErrorAction still overrides the preference.'Caught without -ErrorAction: Cannot find path '/home/sid/errors/config/missing.json' because it does not exist.
An explicit -ErrorAction still overrides the preference.For scripts that run unattended, I start with $ErrorActionPreference = 'Stop' and opt
specific calls out of it. Failing loudly and early is far easier to debug than a script
that ploughed on for 200 lines on bad data.
try, catch, finally
try holds the code that might fail. catch runs if a terminating error happens. finally
always runs, whether the try succeeded, failed, or was left with return. Put cleanup
there: lock files, temporary files, connections, Pop-Location.
$lock = './backup.lock'
New-Item -Path $lock -ItemType File -Force | Out-Null
try {
'lock taken, copying orders.csv'
Copy-Item -Path ./data/orders.csv -Destination ./backup/orders.csv -ErrorAction Stop
'copy finished'
}
catch {
"Backup failed: $($_.Exception.Message)"
}
finally {
Remove-Item -Path $lock
"lock released (lock file exists: $(Test-Path -Path $lock))"
}lock taken, copying orders.csv
Backup failed: Could not find a part of the path '/home/sid/errors/backup/orders.csv'.
lock released (lock file exists: False)Without finally, the failed copy would have left backup.lock behind, and every later run
would think a backup was still in progress. finally also runs on return, which makes it
the place to dispose of .NET objects that hold files open:
function Get-FirstLine {
param([string]$Path)
$reader = [System.IO.StreamReader]::new((Resolve-Path -Path $Path).Path)
try {
return $reader.ReadLine()
}
finally {
$reader.Dispose()
Write-Host 'reader disposed'
}
}
Get-FirstLine -Path ./data/orders.csvorder_id,amount
reader disposedA finally block also runs when the user presses Ctrl+C during the try, which a catch
does not.
Catching specific exception types
A bare catch catches everything. Add a type in brackets to handle only specific errors,
with the most specific types first. To find the type to catch, trigger the error once and
look at $Error[0]:
try { Get-Item -Path ./config/missing.json -ErrorAction Stop } catch { }
$Error[0].Exception.GetType().FullName
try { $null = Get-Content -Path ./config/broken.json -Raw | ConvertFrom-Json -ErrorAction Stop } catch { }
$Error[0].Exception.GetType().FullName
try { [int]::Parse('abc') } catch { }
$Error[0].Exception.GetType().FullName
$Error[0].Exception.InnerException.GetType().FullNameSystem.Management.Automation.ItemNotFoundException
System.ArgumentException
System.Management.Automation.MethodInvocationException
System.FormatExceptionNote the last pair. PowerShell wraps exceptions from .NET methods in a
MethodInvocationException, and the original is in .InnerException. A
catch [System.FormatException] does still match, because PowerShell checks the inner
exception too. Now a config reader that treats "missing" and "malformed" differently:
function Read-Config {
[CmdletBinding()]
param([string]$Path)
try {
Get-Content -Path $Path -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
Write-Warning "No config at $Path, using defaults"
[pscustomobject]@{ port = 8080; logLevel = 'INFO' }
}
catch [System.ArgumentException] {
throw "Config file $Path is not valid JSON: $($_.Exception.Message)"
}
}
foreach ($path in './config/app.json', './config/missing.json', './config/broken.json') {
$config = Read-Config -Path $path
'{0}: port={1} logLevel={2}' -f $path, $config.port, $config.logLevel
}./config/app.json: port=8443 logLevel=WARN
WARNING: No config at ./config/missing.json, using defaults
./config/missing.json: port=8080 logLevel=INFO
Exception: /home/sid/errors/typed-catch.ps1:13
Line |
13 | throw "Config file $Path is not valid JSON: $($_.Exception.Me …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Config file ./config/broken.json is not valid JSON: Conversion from JSON
| failed with error: After parsing a value an unexpected character was
| encountered: ". Path 'host', line 3, position 2.A missing file is an expected situation with a sensible default. A corrupt file is a real
problem, so it's rethrown with a message that names the file. broken.json is missing a
comma after "host": "db01.internal", and the parser points to line 3. One catch block can
list several types: catch [System.IO.IOException], [System.UnauthorizedAccessException] { }.
Inside the catch block: the error record
In a catch block, $_ is an ErrorRecord, not just a message. It tells you what failed,
where, and on what:
try {
Get-Item -Path ./config/missing.json -ErrorAction Stop
}
catch {
$err = $_
"Message: $($err.Exception.Message)"
"Exception type: $($err.Exception.GetType().FullName)"
"Category: $($err.CategoryInfo.Category)"
"ErrorId: $($err.FullyQualifiedErrorId)"
"Target: $($err.TargetObject)"
"Script line: $($err.InvocationInfo.ScriptLineNumber)"
"Line text: $($err.InvocationInfo.Line.Trim())"
"Command: $($err.InvocationInfo.MyCommand)"
"Stack: $($err.ScriptStackTrace)"
}Message: Cannot find path '/home/sid/errors/config/missing.json' because it does not exist.
Exception type: System.Management.Automation.ItemNotFoundException
Category: ObjectNotFound
ErrorId: PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
Target: /home/sid/errors/config/missing.json
Script line: 2
Line text: Get-Item -Path ./config/missing.json -ErrorAction Stop
Command: Get-Item
Stack: at <ScriptBlock>, /home/sid/errors/error-record.ps1: line 2The fields you'll use most:
$_.Exception.Message: the human-readable text, for logs and user messages.$_.Exception: the .NET exception object, for type checks and.InnerException.$_.TargetObject: what the command was working on, here the path. Gold in a loop.$_.FullyQualifiedErrorIdand$_.CategoryInfo: stable identifiers you can branch on, unlike message text, which can change between versions and languages.$_.InvocationInfo: the script, line number, line text and command.$_.ScriptStackTrace: the chain of function calls that led here.
Copy $_ into a variable as the first line of a catch block. Any pipeline inside the
catch rebinds $_ (see Common mistakes). For interactive digging, PowerShell 7's
Get-Error prints the whole record, nested exceptions included:
Get-Item -Path ./config/missing.json -ErrorAction SilentlyContinue
Get-Error -Newest 1Exception :
Type : System.Management.Automation.ItemNotFoundException
ErrorRecord :
[…]
Message : Cannot find path '/home/sid/e
rrors/config/missing.json' because it does not exist.
Source : System.Management.Automation
HResult : -2146233087
StackTrace :
[…]
TargetObject : /home/sid/errors/config/missing.
json
CategoryInfo : ObjectNotFound: (/home/sid/shellrag-…config/missing.jso
n:String) [Get-Item], ItemNotFoundException
FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemComma
nd
InvocationInfo :
MyCommand : Get-Item
ScriptLineNumber : 1
[…]
ScriptStackTrace : at <ScriptBlock>, /home/sid/erro
rs/get-error.ps1: line 1(The full output was about 70 lines and included the .NET stack trace.) Get-Error doesn't
exist in Windows PowerShell 5.1. There, $Error[0] | Format-List * -Force is the nearest
equivalent.
throw versus Write-Error
Your own functions report failures in one of two ways, and they mean different things:
Write-Errorwrites a non-terminating error: "this item failed, carry on with the others". The caller decides with-ErrorActionwhether that should stop them.throwraises a terminating error: "I can't continue at all".
function Get-ServicePort {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Service)
$ports = @{ api = 8080; auth = 8443 }
if (-not $ports.ContainsKey($Service)) {
Write-Error -Message "Unknown service '$Service'" -Category ObjectNotFound `
-TargetObject $Service -ErrorId 'UnknownService'
return
}
$ports[$Service]
}
'api', 'billing', 'auth' | ForEach-Object { Get-ServicePort -Service $_ }
'--- with -ErrorAction Stop:'
try {
Get-ServicePort -Service billing -ErrorAction Stop
}
catch {
"caught $($_.FullyQualifiedErrorId) for target '$($_.TargetObject)'"
}8080
Get-ServicePort: /home/sid/errors/write-error.ps1:14
Line |
14 | … ', 'billing', 'auth' | ForEach-Object { Get-ServicePort -Service $_ }
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Unknown service 'billing'
8443
--- with -ErrorAction Stop:
caught UnknownService,Get-ServicePort for target 'billing'billing failed, and auth was still processed. With -ErrorAction Stop, the caller turned
it into a catchable error carrying the -ErrorId and -TargetObject we supplied. Always
follow Write-Error with return if the function can't produce a result for that input.
throw accepts a string, but throwing a typed exception lets callers catch it precisely:
function Get-ReleaseManifest {
param([string]$Path)
if (-not (Test-Path -Path $Path)) {
throw [System.IO.FileNotFoundException]::new("Release manifest not found", $Path)
}
Get-Content -Path $Path
}
try {
Get-ReleaseManifest -Path ./releases/2026-11-09/manifest.txt
}
catch [System.IO.FileNotFoundException] {
"Missing file: $($_.Exception.FileName)"
}
throw 'plain string throw'Missing file: ./releases/2026-11-09/manifest.txt
Exception: /home/sid/errors/throw-types.ps1:16
Line |
16 | throw 'plain string throw'
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
| plain string throwA string throw becomes a generic RuntimeException (shown as Exception:), which callers
can only catch with a bare catch.
One subtlety for advanced functions: throw is script-terminating, so it ends the whole
script unless caught. $PSCmdlet.ThrowTerminatingError() is only statement-terminating,
which is how built-in cmdlets behave:
function Stop-WithThrow {
[CmdletBinding()]
param()
throw 'stopped with throw'
}
function Stop-WithThrowTerminating {
[CmdletBinding()]
param()
$record = [System.Management.Automation.ErrorRecord]::new(
[System.InvalidOperationException]::new('stopped with ThrowTerminatingError'),
'DeployStopped',
[System.Management.Automation.ErrorCategory]::InvalidOperation,
$null)
$PSCmdlet.ThrowTerminatingError($record)
}
Stop-WithThrowTerminating
'after ThrowTerminatingError: script continues'
Stop-WithThrow
'after throw: never printed'Stop-WithThrowTerminating: /home/sid/errors/throw-script-vs-statement.ps1:17
Line |
17 | Stop-WithThrowTerminating
| ~~~~~~~~~~~~~~~~~~~~~~~~~
| stopped with ThrowTerminatingError
after ThrowTerminatingError: script continues
Exception: /home/sid/errors/throw-script-vs-statement.ps1:4
Line |
4 | throw 'stopped with throw'
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
| stopped with throwThe script carried on after ThrowTerminatingError and stopped at throw, with exit code 1.
The ThrowTerminatingError message also points at the caller's line (17),
not inside the function, just like a built-in cmdlet's error. That makes it the better choice
for reusable module functions. In your own top-level scripts, throw is simpler and fine.
The $Error collection
Every error, whether shown, silenced with SilentlyContinue or caught, is added to the
automatic $Error list, newest first:
$Error.Clear()
Get-Item -Path ./first-missing.txt -ErrorAction SilentlyContinue
Get-Item -Path ./second-missing.txt -ErrorAction SilentlyContinue
"Errors recorded: $($Error.Count)"
"Newest: $($Error[0].TargetObject)"
"Oldest: $($Error[-1].TargetObject)"Errors recorded: 2
Newest: /home/sid/errors/second-missing.txt
Oldest: /home/sid/errors/first-missing.txt$Error[0] is the quickest way to inspect "what just went wrong" at the prompt. Don't use
$Error.Count to decide whether your script succeeded, though. It's session-wide, it includes
errors from modules and from your profile, and it's full of errors you deliberately ignored.
Use try/catch or -ErrorVariable for decisions.
Collecting failures with -ErrorVariable
-ErrorVariable (alias -ev) stores just this command's errors in a variable you name,
with no $ in the name. A + prefix appends instead of overwriting. It's ideal for "process
everything, then report what failed":
$configs = 'app', 'web01', 'web02', 'db01' | ForEach-Object { "./config/$_.json" }
$found = Get-Item -Path $configs -ErrorAction SilentlyContinue -ErrorVariable missing
"Found $(@($found).Count), missing $($missing.Count):"
$missing | ForEach-Object { " $($_.TargetObject)" }
Get-Item -Path ./config/db.json, ./config/cache.json -ErrorAction SilentlyContinue -ErrorVariable +missing | Out-Null
"After appending with +missing: $($missing.Count) errors"Found 2, missing 2:
/home/sid/errors/config/web02.json
/home/sid/errors/config/db01.json
After appending with +missing: 3 errorsCombining SilentlyContinue with -ErrorVariable keeps the console clean and still lets you
report every failure at the end, for example in a summary email. -WarningVariable does the
same for warnings.
Native commands: exit codes, not exceptions
External programs (git, robocopy, terraform, ls, grep) don't throw PowerShell
errors. They return an exit code, which PowerShell puts in $LASTEXITCODE. $? is
$false when the last command failed:
ls /etc/hostname /var/empty-dir-that-does-not-exist
"exit code: $LASTEXITCODE `$?: $?"
try {
ls /var/empty-dir-that-does-not-exist
'try block finished; native failures do not throw by default'
}
catch {
'never caught'
}/usr/bin/ls: cannot access '/var/empty-dir-that-does-not-exist': No such file or directory
/etc/hostname
exit code: 2 $?: False
/usr/bin/ls: cannot access '/var/empty-dir-that-does-not-exist': No such file or directory
try block finished; native failures do not throw by defaulttry/catch and $ErrorActionPreference = 'Stop' didn't see the failure at all. The classic
pattern is to check $LASTEXITCODE right after the call:
git pull
if ($LASTEXITCODE -ne 0) { throw "git pull failed with exit code $LASTEXITCODE" }PowerShell 7.4 added $PSNativeCommandUseErrorActionPreference. Set it to $true and a
non-zero exit code becomes a real error that follows $ErrorActionPreference:
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
try {
ls /var/empty-dir-that-does-not-exist
'not reached'
}
catch {
"caught: $($_.Exception.Message)"
"type: $($_.Exception.GetType().FullName)"
}/usr/bin/ls: cannot access '/var/empty-dir-that-does-not-exist': No such file or directory
caught: Program "ls" ended with non-zero exit code: 2 (0x02).
type: System.Management.Automation.NativeCommandExitExceptionUse it with care, because not every non-zero exit code means failure. grep returns 1 for
"no match", robocopy returns 1 to 7 for various kinds of success, and diff returns 1 for
"files differ":
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
grep -q 'FATAL' ./data/orders.csv
'grep found nothing, but that line is never reached'NativeCommandExitException: /home/sid/errors/native-grep.ps1:4
Line |
4 | grep -q 'FATAL' ./data/orders.csv
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Program "grep" ended with non-zero exit code: 1 (0x01).For commands like that, switch the preference off in a child scope and interpret the code yourself:
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
& {
$PSNativeCommandUseErrorActionPreference = $false
grep -q 'FATAL' ./data/orders.csv
}
if ($LASTEXITCODE -eq 1) { 'no FATAL lines' } elseif ($LASTEXITCODE -gt 1) { throw "grep failed with $LASTEXITCODE" }no FATAL linesRedirecting a native command's stderr with 2>&1 turns each stderr line into an
ErrorRecord in the output. In PowerShell 7 that's harmless:
$output = ls /etc/hostname /var/empty-dir-that-does-not-exist 2>&1
$output | ForEach-Object { '{0,-12} {1}' -f $_.GetType().Name, $_ }
"`$Error.Count = $($Error.Count)"String /etc/hostname
ErrorRecord /usr/bin/ls: cannot access '/var/empty-dir-that-does-not-exist': No such file or directory
$Error.Count = 0In Windows PowerShell 5.1 the same redirection also records the lines as errors, and they
are displayed as scary NativeCommandError blocks. Running
cmd.exe /c "dir C:\does-not-exist-ps-c" 2>&1 there printed:
cmd.exe : File Not Found
[…]
+ CategoryInfo : NotSpecified: (File Not Found:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandErrorThere, $Error.Count was 1 after the redirect. Worse, with $ErrorActionPreference = 'Stop',
cmd.exe /c "echo progress message 1>&2" 2>&1 jumped straight to the catch block with the
message progress message, even though the command succeeded with exit code 0. That's how
5.1 scripts die on harmless stderr output such as git's progress messages. If you maintain 5.1 scripts that call native
tools, don't redirect stderr into the success stream under Stop, and always judge success
by $LASTEXITCODE.
trap, briefly
trap is the pre-try mechanism, from PowerShell 1.0. A trap block catches any
terminating error in its scope. continue resumes at the next statement, and break
rethrows:
trap {
"trap caught: $($_.Exception.Message)"
continue
}
'start'
Get-Item -Path ./config/missing.json -ErrorAction Stop
'after the failing line'start
trap caught: Cannot find path '/home/sid/errors/config/missing.json' because it does not exist.
after the failing lineYou'll meet trap in old scripts. For new code, try/catch is clearer about which lines
it covers.
Set-StrictMode: catching your own typos
Many PowerShell "errors" never raise an error at all. A misspelled variable is just $null,
and a misspelled property is just $null:
function Get-Total {
param([int[]]$Amounts)
$total = 0
foreach ($amount in $Amounts) { $total += $amount }
$totl
}
"Total: [$(Get-Total -Amounts 10, 20, 30)]"
$config = Get-Content -Path ./config/app.json -Raw | ConvertFrom-Json
$port = $config.Prot
"Port: [$port]"Total: []
Port: []Two bugs, zero errors. Add Set-StrictMode -Version Latest at the top of the same script:
InvalidOperation: /home/sid/errors/strict-on.ps1:7
Line |
7 | $totl
| ~~~~~
| The variable '$totl' cannot be retrieved because it has not been set.
Total: []
PropertyNotFoundException: /home/sid/errors/strict-on.ps1:12
Line |
12 | $port = $config.Prot
| ~~~~~~~~~~~~~~~~~~~~
| The property 'Prot' cannot be found on this object. Verify that the
| property exists.
InvalidOperation: /home/sid/errors/strict-on.ps1:13
Line |
13 | "Port: [$port]"
| ~~~~~
| The variable '$port' cannot be retrieved because it has not been set.Both bugs are now reported at the exact line. The script still carried on, because these are
statement-terminating errors. Strict mode makes mistakes visible, and
$ErrorActionPreference = 'Stop' makes them fatal. Use both in scripts. Strict mode
applies to the scope it's set in and its children, so setting it at the top of a script
covers the script's functions. It doesn't reach into modules you import.
Logging errors to a file
Unattended scripts need a record of what failed. A small helper that turns an error record
into one log line keeps every catch block short:
function Write-ErrorLog {
param(
[Parameter(Mandatory)]
[System.Management.Automation.ErrorRecord]$ErrorRecord,
[string]$Path = './logs/errors.log'
)
$line = '{0:yyyy-MM-ddTHH:mm:ss} ERROR {1}:{2} {3}: {4}' -f (Get-Date),
(Split-Path -Path $ErrorRecord.InvocationInfo.ScriptName -Leaf),
$ErrorRecord.InvocationInfo.ScriptLineNumber,
$ErrorRecord.Exception.GetType().Name,
$ErrorRecord.Exception.Message
Add-Content -Path $Path -Value $line
}
foreach ($file in './config/app.json', './config/missing.json', './config/broken.json') {
try {
$null = Get-Content -Path $file -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
"ok: $file"
}
catch {
Write-ErrorLog -ErrorRecord $_
"failed: $file (logged)"
}
}
Get-Content -Path ./logs/errors.logok: ./config/app.json
failed: ./config/missing.json (logged)
failed: ./config/broken.json (logged)
2026-11-10T01:20:32 ERROR log-errors.ps1:17 ItemNotFoundException: Cannot find path '/home/sid/errors/config/missing.json' because it does not exist.
2026-11-10T01:20:32 ERROR log-errors.ps1:17 ArgumentException: Conversion from JSON failed with error: After parsing a value an unexpected character was encountered: ". Path 'host', line 3, position 2.One line per error, with a sortable timestamp, the location and the exception type, is easy
to grep and easy to ship to a log collector. For a full record of everything a script
printed, Start-Transcript -Path ./logs/run.log at the top and Stop-Transcript in a
finally block capture the whole console session.
A robust pattern for scripts
Everything above combines into one template. This is a backup script meant for cron or Task Scheduler. It refuses to run twice at once, verifies its copy with a hash, logs every outcome, always cleans up its own lock, and reports success or failure through its exit code, which is the only thing a scheduler can see:
#Requires -Version 7.2
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Source,
[Parameter(Mandatory)]
[string]$Destination,
[string]$LogFile = (Join-Path -Path $PSScriptRoot -ChildPath 'backup.log')
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
function Write-Log {
param([string]$Message, [string]$Level = 'INFO')
$line = '{0:yyyy-MM-dd HH:mm:ss} {1,-5} {2}' -f (Get-Date), $Level, $Message
Add-Content -Path $LogFile -Value $line
Write-Verbose $line
}
$lockFile = Join-Path -Path $Destination -ChildPath '.backup.lock'
$lockTaken = $false
try {
Write-Log "Backup started: $Source -> $Destination"
if (-not (Test-Path -Path $Destination)) {
$null = New-Item -ItemType Directory -Path $Destination
}
if (Test-Path -Path $lockFile) {
throw "Another backup is running (lock file $lockFile exists)"
}
$null = New-Item -ItemType File -Path $lockFile
$lockTaken = $true
$target = Join-Path -Path $Destination -ChildPath ('orders-{0:yyyyMMdd-HHmmss}.csv' -f (Get-Date))
Copy-Item -Path $Source -Destination $target
$sourceHash = (Get-FileHash -Path $Source).Hash
$targetHash = (Get-FileHash -Path $target).Hash
if ($sourceHash -ne $targetHash) {
throw "Hash mismatch after copy: $target"
}
Write-Log "Backup OK: $(Split-Path -Path $target -Leaf) sha256=$($sourceHash.Substring(0, 12))"
$exitCode = 0
}
catch {
Write-Log -Level ERROR -Message ("{0} (line {1})" -f $_.Exception.Message, $_.InvocationInfo.ScriptLineNumber)
$exitCode = 1
}
finally {
if ($lockTaken) {
Remove-Item -Path $lockFile -Force -ErrorAction Continue
}
}
exit $exitCodeI ran it three times from Bash, the way a scheduler would: once normally, once with a source
file that doesn't exist, and once after creating a stale lock file by hand. The final
cat shows the log:
pwsh -NoProfile -NonInteractive -File ./Backup-Orders.ps1 -Source ../data/orders.csv -Destination ../backups
echo "exit code: $?"
pwsh -NoProfile -NonInteractive -File ./Backup-Orders.ps1 -Source ../data/missing.csv -Destination ../backups
echo "exit code: $?"
touch ../backups/.backup.lock
pwsh -NoProfile -NonInteractive -File ./Backup-Orders.ps1 -Source ../data/orders.csv -Destination ../backups
echo "exit code: $?"
ls -A ../backups
cat backup.logexit code: 0
exit code: 1
exit code: 1
.backup.lock
orders-20261110-012035.csv
2026-11-10 01:20:35 INFO Backup started: ../data/orders.csv -> ../backups
2026-11-10 01:20:35 INFO Backup OK: orders-20261110-012035.csv sha256=93384FA1B521
2026-11-10 01:20:36 INFO Backup started: ../data/missing.csv -> ../backups
2026-11-10 01:20:36 ERROR Cannot find path '/home/sid/errors/data/missing.csv' because it does not exist. (line 40)
2026-11-10 01:20:37 INFO Backup started: ../data/orders.csv -> ../backups
2026-11-10 01:20:37 ERROR Another backup is running (lock file ../backups/.backup.lock exists) (line 34)The pieces, and why each one is there:
#Requiresand[CmdletBinding()]withMandatoryparameters fail before any work starts.Set-StrictModeplus$ErrorActionPreference = 'Stop'turn typos and cmdlet failures into catchable errors.$PSNativeCommandUseErrorActionPreferencedoes the same for any native tools the script calls.- One
tryaround the whole body means there's one place where failures are logged and converted into an exit code. $lockTakenmakes surefinallyonly deletes a lock this run created. The third run correctly left the stale lock alone for a human to investigate.exit $exitCodeafterfinally. Exiting from insidecatchwould also runfinally(I checked:exit 3in acatchstill printed thefinallyoutput, and the exit code was 3), but a single exit at the end is easier to follow.
My first version of this script used Remove-Item -Path $lockFile without -Force, and the
cleanup failed with You do not have sufficient access rights to perform this operation or the item is hidden, system, or read only. On Linux, PowerShell treats dot-files as hidden, and
Remove-Item refuses hidden items without -Force. On Windows, the same happens with files
that have the Hidden attribute.
Where you'll use this
- Scheduled jobs (cron, Task Scheduler, systemd timers): the template above. The exit code is how the scheduler, and whatever monitors it, knows the job failed.
- CI/CD pipelines (Jenkins, GitHub Actions, Azure DevOps): a step fails when the script
exits non-zero. A script that swallows errors and exits 0 produces green builds that
deployed nothing.
$PSNativeCommandUseErrorActionPreferenceis especially useful here, because pipelines calldotnet,npm,terraformandgitconstantly. - Bulk administration:
-ErrorAction SilentlyContinue -ErrorVariable +failedacross hundreds of users, mailboxes or servers, then a report of exactly which ones failed and why. - Module functions:
Write-Errorfor per-item failures and$PSCmdlet.ThrowTerminatingError()for fatal ones, so callers can control behaviour with-ErrorActionjust as they do with built-in cmdlets.
Common mistakes
Wrapping a non-terminating error in try/catch
Shown at the top: try { Get-Item ./missing } doesn't catch anything, because the error is
non-terminating. Add -ErrorAction Stop to the call, or set
$ErrorActionPreference = 'Stop' for the script.
Using $_ inside a pipeline in the catch block
$servers = 'web01', 'web02'
try {
Get-Item -Path ./config/missing.json -ErrorAction Stop
}
catch {
$servers | ForEach-Object { "notify ${_}: config error [$($_.Exception.Message)]" }
}notify web01: config error []
notify web02: config error []Inside ForEach-Object, $_ is the current server, not the error, so the message is empty.
Save the error first:
$servers = 'web01', 'web02'
try {
Get-Item -Path ./config/missing.json -ErrorAction Stop
}
catch {
$err = $_
$servers | ForEach-Object { "notify ${_}: config error [$($err.Exception.Message)]" }
}notify web01: config error [Cannot find path '/home/sid/errors/config/missing.json' because it does not exist.]
notify web02: config error [Cannot find path '/home/sid/errors/config/missing.json' because it does not exist.]A typo in the exception type
try {
Get-Item -Path ./config/missing.json -ErrorAction Stop
}
catch [System.IO.FileNotFound] {
'never reached'
}InvalidOperation: /home/sid/errors/bad-type.ps1:4
Line |
4 | catch [System.IO.FileNotFound] {
| ~~~~~~~~~~~~~~~~~~~~~~~~
| Unable to find type [System.IO.FileNotFound].The type name is only resolved when an error actually arrives, so this bug hides until the
day the failure it was meant to handle happens. The real type is
System.IO.FileNotFoundException, and it wouldn't match here anyway, because Get-Item
throws ItemNotFoundException. Always discover types from $Error[0] as shown earlier, and
test your catch blocks by forcing the failure once.
Silencing errors to make output clean
The opening example: SilentlyContinue set script-wide turned a failed copy into data loss.
If an error is expected, handle that error (Test-Path, a typed catch). If it isn't
expected, you want to see it.
Trusting native commands to stop the script
terraform apply failing inside a try block doesn't trigger the catch. Check
$LASTEXITCODE after every native call that matters, or opt in to
$PSNativeCommandUseErrorActionPreference on 7.4+.
Summary
- Non-terminating errors (most cmdlet failures) report and carry on, and
try/catchignores them.-ErrorAction Stopor$ErrorActionPreference = 'Stop'makes them catchable. - Terminating errors are statement-terminating (.NET exceptions,
ThrowTerminatingError) or script-terminating (throw,Stop). The first kind lets an unprotected script continue. finallyalways runs, even afterreturnor Ctrl+C. Clean up locks, temp files and handles there, and only clean up what this run created.- Catch specific types, most specific first. Find the type with
$Error[0].Exception.GetType().FullName. Incatch, copy$_to a variable before running any pipeline. Write-Errormeans "this item failed",throwmeans "I can't continue". Typed exceptions and-ErrorId/-TargetObjectlet callers react precisely.- Native programs set
$LASTEXITCODEand never throw, unless you set$PSNativeCommandUseErrorActionPreference = $true(7.4+). Remember that exit codes like grep's 1 aren't always failures. Set-StrictMode -Version Latestturns misspelled variables and properties into errors. Pair it with$ErrorActionPreference = 'Stop'.- Unattended scripts: one
tryaround the work, log every failure with the error record's details, andexitnon-zero on failure so the scheduler or CI system notices.
Exercises
Loop over ./config/app.json.bak (which exists) and ./config/old.json.bak (which doesn't),
deleting each with Remove-Item. Print removed <path> on success. For a missing file,
print nothing to remove at <path> using the error record's target object, and catch only
the "not found" exception type.
Show Solution
foreach ($path in './config/app.json.bak', './config/old.json.bak') {
try {
Remove-Item -Path $path -ErrorAction Stop
"removed $path"
}
catch [System.Management.Automation.ItemNotFoundException] {
"nothing to remove at $($_.TargetObject)"
}
}removed ./config/app.json.bak
nothing to remove at /home/sid/errex/config/old.json.bakWithout -ErrorAction Stop, the catch never runs and PowerShell prints its own error
instead. Catching only ItemNotFoundException means a different failure, such as a
permission error, still surfaces.
Write Test-JsonFile, which accepts files from Get-ChildItem through the pipeline and
outputs one object per file with File, Valid ($true/$false) and Reason (the error
message for invalid files). A bad file must not stop the remaining files from being checked.
Show Solution
function Test-JsonFile {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[string]$Path
)
process {
try {
$null = Get-Content -LiteralPath $Path -Raw -ErrorAction Stop |
ConvertFrom-Json -ErrorAction Stop
[pscustomobject]@{ File = Split-Path -Path $Path -Leaf; Valid = $true; Reason = '' }
}
catch {
[pscustomobject]@{ File = Split-Path -Path $Path -Leaf; Valid = $false; Reason = $_.Exception.Message }
}
}
}
Get-ChildItem -Path ./config -Filter *.json | Test-JsonFile | Format-Table -WrapFile Valid Reason
---- ----- ------
app.json True
broken.json False Conversion from JSON failed with error: After parsing a value
an unexpected character was encountered: ". Path 'host', lin
e 1, position 17.
web01.json True The try/catch sits inside process, so each file is handled on its own. Turning
the error into data (Valid = $false) is often more useful than an error message, because
you can filter it, count it or export it.
Write Get-ErrorLineCount, which runs grep -c ' ERROR ' on a file and returns the number
of matching lines. grep exits 0 when it finds matches, 1 when it finds none, and 2 or higher
on a real error. Return 0 for exit code 1, and throw for anything above 1. Test it on a log
with errors, one without, and a file that doesn't exist.
Show Solution
function Get-ErrorLineCount {
param([Parameter(Mandatory)][string]$Path)
$count = grep -c ' ERROR ' $Path
switch ($LASTEXITCODE) {
0 { [int]$count }
1 { 0 }
default { throw "grep failed on $Path with exit code $LASTEXITCODE" }
}
}
foreach ($log in './data/api.log', './data/auth.log', './data/gone.log') {
try {
'{0,-16} {1}' -f $log, (Get-ErrorLineCount -Path $log)
}
catch {
"ERROR: $($_.Exception.Message)"
}
}./data/api.log 1
./data/auth.log 0
/usr/bin/grep: ./data/gone.log: No such file or directory
ERROR: grep failed on ./data/gone.log with exit code 2$LASTEXITCODE has to be read immediately after the native call, before another native
command overwrites it. The grep message on the third line is grep's own stderr, passed
straight through to the console.
Write Move-Verified -Path <file> -Destination <folder>. It copies the file, compares SHA256
hashes, and deletes the source only if they match. If anything fails, it removes any partial
copy it created and rethrows the original error. Show one successful move and one into a
folder that doesn't exist, then list what's left in ./data and ./archive.
Show Solution
function Move-Verified {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][string]$Destination
)
$ErrorActionPreference = 'Stop'
$target = Join-Path -Path $Destination -ChildPath (Split-Path -Path $Path -Leaf)
$copied = $false
try {
Copy-Item -Path $Path -Destination $target
$copied = $true
if ((Get-FileHash -Path $Path).Hash -ne (Get-FileHash -Path $target).Hash) {
throw "Hash mismatch for $target"
}
Remove-Item -Path $Path
"moved $Path -> $target"
}
catch {
if ($copied -and (Test-Path -Path $target)) {
Remove-Item -Path $target
Write-Warning "removed partial copy $target"
}
throw
}
}
Move-Verified -Path ./data/orders-2026-11-08.csv -Destination ./archive
try {
Move-Verified -Path ./data/orders-2026-11-09.csv -Destination ./no-such-folder
}
catch {
"move failed: $($_.Exception.Message)"
}
(Get-ChildItem -Path ./data, ./archive -Filter *.csv).Namemoved ./data/orders-2026-11-08.csv -> ./archive/orders-2026-11-08.csv
move failed: Could not find a part of the path '/home/sid/errex/no-such-folder/orders-2026-11-09.csv'.
orders-2026-11-09.csv
orders-2026-11-08.csvThe failed move left the source in ./data untouched. A bare throw inside catch
rethrows the original error record, so the caller sees the real cause rather than a generic
message. Setting $ErrorActionPreference inside the function only affects the function's
scope, so callers keep their own preference.
Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2) and Windows PowerShell 5.1 on
Windows 11, November 2026. Every example was run as shown with pwsh -NoProfile -File. The
backup script was run from Bash with -NonInteractive, as a scheduler would run it, and the
Get-Error output was trimmed where marked. I also checked the smaller claims directly:
a typed catch matches the inner exception, strict mode doesn't reach into an imported
module, and Get-Error doesn't exist in 5.1. On Windows I only ran read-only commands,
including a cmd.exe /c dir of a missing folder to capture the 5.1 NativeCommandError
display. The git pull snippet illustrates the pattern and was not run. Paths from the test machine's scratch directories are shown shortened to /home/sid/….
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.