Handling errors and exceptions in PowerShell
Posted: (EET/GMT+2)
PowerShell has two kinds of errors: terminating (throw) and non-terminating (cmdlet reports an error but continues). If you want to make sure your PowerShell scripts continue running even if there are errors, use the try/catch block. This way, you control what happens when terminating errors occur.
Here's an example of the basic pattern:
try {
# force non-terminating errors to behave like exceptions
$content = Get-Content "C:\does-not-exist.txt" -ErrorAction Stop
"Length: $($content.Length)"
}
catch [System.IO.IOException] {
Write-Warning "IO error: $($_.Exception.Message)"
}
catch {
Write-Error "Unexpected: $($_.Exception.Message)"
}
finally {
# the "finally" block lways runs
"Done."
}
In essence, PowerShell exception handling is very much like the one in C#. This is no coincidence, as PowerShell is based on .NET.
Here's a quick list of useful switches and variables:
-ErrorAction Stop # make cmdlets throw on error -ErrorVariable err # capture errors into $err $ErrorActionPreference # global default for the error action (for example, "Stop") $? # success of last command (True/False) $LASTEXITCODE # native process exit code (a number, zero often means success) throw "message" # generate your own terminating error
The try/catch block is a good choice for most scripts. Keep your try blocks small, catch specific exception types when you can, and log enough detail to fix the issue when it occurs.