PowerShell Error Handling
- Similar to most languages, PowerShell errors can be handled with
try
/catch
blocks.
try { 0/0 }
catch {
Write-Host "the error: $_" -fore cyan
}
throw "error"
catch [System.IO.FileNotFoundException] {}
. Can chain severalcatch
statements.- PowerShell only handles terminating errors in try/catch blocks (as opposed to non-terminating)
- Traps can also be used to handle all terminating errors within a scope. Can be used to continue execution upon a terminating error.
function foo {
trap {"error found"}
0/0
write-host "still here"
}
Related: two common parameters
-ErrorAction [Continue [default] | Stop | SilentlyContinue | Inquire]
.Stop
is terminating. e.g.mv a b -ErrorAction Stop
,mv c d -ea SilentlyContinue
-ErrorVariable var_name
- errors are assigned to this variable. Default:$error
. Can also pass+var_name
to append and not clear the variable.var_name
is of typeArrayList
. Default:$error
. e.g.mv a a -ErrorVariable e
,mv a a -ev e
</i>