PowerShell Error Handling
Things go wrong: files are missing, servers don't answer, input is invalid. Good scripts expect errors and handle them deliberately. PowerShell has two kinds of errors, and understanding the difference is the key to handling them correctly.
Terminating vs non-terminating errors
| Non-terminating | Terminating | |
|---|---|---|
| Example | Get-Item missing.txt |
throw, 1/0, a parse error |
| What happens | error is reported, the command continues with the next item | the current statement (and script) stops |
Caught by try/catch? |
no (unless made terminating) | yes |
Get-Item ./missing.txt, ./also-missing.txt
'The script continues after non-terminating errors'Get-Item: /w/main.ps1:1
Line |
1 | Get-Item ./missing.txt, ./also-missing.txt
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot find path '/tmp/missing.txt' because it does not exist.
Get-Item: /w/main.ps1:1
Line |
1 | Get-Item ./missing.txt, ./also-missing.txt
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot find path '/tmp/also-missing.txt' because it does not exist.
The script continues after non-terminating errors
Most cmdlet errors are non-terminating: a cmdlet processing 100 files reports the one that failed and carries on with the rest. That's useful, but it means try/catch won't see them by default.
try / catch / finally
Code in try runs; if a terminating error occurs, control jumps to catch. finally always runs, error or not, which makes it the place for cleanup:
try {
'Opening connection'
throw 'Connection refused'
'never printed'
}
catch {
"Caught: $($_.Exception.Message)"
}
finally {
'Closing connection (always runs)'
}Opening connection
Caught: Connection refused
Closing connection (always runs)
Inside catch, $_ is an ErrorRecord. Its most useful parts are $_.Exception.Message (the text), $_.Exception.GetType() (the type), $_.InvocationInfo.ScriptLineNumber (the line) and $_.FullyQualifiedErrorId.
-ErrorAction Stop: make cmdlet errors catchable
Add -ErrorAction Stop to turn a cmdlet's non-terminating errors into terminating ones, so catch sees them:
try {
Get-Item ./missing.txt -ErrorAction Stop
'not reached'
}
catch {
"Could not read the file: $($_.Exception.Message)"
}
# Or for the whole script:
$ErrorActionPreference = 'Stop'
try { Get-Item ./missing.txt } catch { 'caught again, thanks to the preference' }Could not read the file: Cannot find path '/tmp/missing.txt' because it does not exist.
caught again, thanks to the preference
-ErrorAction value |
Effect |
|---|---|
Continue (default) |
show the error, keep going |
SilentlyContinue |
hide the error, keep going (still recorded in $Error) |
Ignore |
hide it and don't record it |
Stop |
turn it into a terminating error |
Inquire |
ask the user |
Catching specific exception types
You can have several catch blocks, each for a particular .NET exception type. The first matching block wins; a catch without a type catches everything else:
function Read-Number([string]$Path) {
try {
$text = Get-Content $Path -ErrorAction Stop
$value = [int]$text
100 / $value
}
catch [System.Management.Automation.ItemNotFoundException] {
"No such file: $Path"
}
catch [System.Management.Automation.RuntimeException] {
"Bad content in ${Path}: $($_.Exception.InnerException.GetType().Name)"
}
catch {
"Something else: $($_.Exception.Message)"
}
}
Set-Content ./zero.txt '0'
Set-Content ./word.txt 'ten'
Set-Content ./four.txt '4'
Read-Number ./nothing.txt
Read-Number ./zero.txt
Read-Number ./word.txt
Read-Number ./four.txtNo such file: ./nothing.txt
Bad content in ./zero.txt: DivideByZeroException
Bad content in ./word.txt: PSInvalidCastException
25
PowerShell wraps many .NET errors in a RuntimeException; the original error is in .InnerException (DivideByZeroException, PSInvalidCastException, …).
Throwing your own errors
Use throw to stop with a terminating error. For functions, Write-Error reports a non-terminating error that callers can handle with -ErrorAction:
function Set-Age {
param([int]$Age)
if ($Age -lt 0) { throw [System.ArgumentOutOfRangeException]::new('Age', 'Age cannot be negative') }
"Age set to $Age"
}
try { Set-Age -Age -5 }
catch [System.ArgumentOutOfRangeException] {
"Invalid argument '$($_.Exception.ParamName)'"
}
function Test-Server {
[CmdletBinding()] # needed for -ErrorAction to work
param([string]$Name)
if ($Name -like 'old*') { Write-Error "Server $Name is retired"; return }
"$Name ok"
}
'web01', 'old02', 'db01' | ForEach-Object { Test-Server $_ -ErrorAction SilentlyContinue }Invalid argument 'Age'
web01 ok
db01 ok
The retired server's error was hidden by -ErrorAction SilentlyContinue, and the loop carried on. That parameter only exists because of [CmdletBinding()]: a simple function without it would ignore the request and print the error anyway.
$Error and -ErrorVariable
Every error is added to the automatic list $Error (newest first). -ErrorVariable collects the errors of one command into a variable of your choice:
$Error.Clear()
Get-Item ./a.txt, ./b.txt -ErrorAction SilentlyContinue -ErrorVariable problems
"Errors in `$problems: $($problems.Count)"
"Newest in `$Error: $($Error[0].Exception.Message)"
$problems | ForEach-Object { $_.TargetObject }Errors in $problems: 2
Newest in $Error: Cannot find path '/tmp/b.txt' because it does not exist.
/tmp/a.txt
/tmp/b.txt
-ErrorVariable +name (with a plus) appends instead of overwriting. Errors from native programs don't land in $Error; check $LASTEXITCODE (or $?) after running them.
What an uncaught error looks like
When nothing catches an error, PowerShell 7 prints it in its concise view: the command, the file and line, a marker under the failing code, and the message:
'before'
[int]::Parse('12x')
'after (the error above was terminating for that statement only)'before
MethodInvocationException: /w/main.ps1:2
Line |
2 | [int]::Parse('12x')
| ~~~~~~~~~~~~~~~~~~~
| Exception calling "Parse" with "1" argument(s): "The input string '12x'
| was not in a correct format."
after (the error above was terminating for that statement only)
Tip: A good default for automation scripts:
$ErrorActionPreference = 'Stop'at the top, thentry/catcharound the operations you expect might fail.
Test yourself
Why doesn't try { Get-Item missing.txt } catch { 'x' } print 'x' by default?
- Get-Item never fails
- Get-Item's error is non-terminating, so catch doesn't see it
- catch needs a type
- try only works in functions
When does a finally block run?
- Only after an error
- Only when there is no error
- Always, after try (and catch)
- Never in scripts
Inside a catch block, what is the usual way to get the error text?
- $Error.Text
- $_.Exception.Message
- $catch.Message
- $LASTEXITCODE