PowerShell Error Handling
- Similar to most languages, PowerShell errors can be handled with
try/catchblocks.
try { 0/0 }
catch {
Write-Host "the error: $_" -fore cyan
}
throw "error"catch [System.IO.FileNotFoundException] {}. Can chain severalcatchstatements.- 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].Stopis 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_nameto append and not clear the variable.var_nameis of typeArrayList. Default:$error. e.g.mv a a -ErrorVariable e,mv a a -ev e</i>