PowerShell: Error Handling

Error handling is one of the key parts of a good PowerShell script. A script that runs correctly once may not run correctly every time. When the unexpected happens, we turn to exception handling.

Errors categorized two types

  • Terminating
  • Non-Terminating

Terminating Error:

A terminating error is an error that will stop a function or statement completely. Syntax errors, non-existent cmdlets, run out of memory or other fatal errors are the examples for terminating errors. Terminating errors can be caught and handled.

Non-Terminating Error:

Non-terminating errors allow Powershell to continue the execution despite the failure. Under normal circumstances, they cannot be caught.

It is possible to treat all errors as terminating using ErrorActionPreference variable by adding “$ErrorActionPreference = Stop” at first line.

Available choices for Error Action Preference:

  • SilentlyContinue – error messages are suppressed and execution continues.
  • Stop – forces execution to stop, behaving like a terminating error.
  • Continue – the default option. Errors will display and execution will continue.
  • Inquire – prompt the user for input to see if we should proceed.
  • Ignore – the error is ignored and not logged to the error stream. Has very restricted usage scenarios.

Try Catch Finally

Use Try block to define a section of a script in which you want PowerShell to monitor for errors.

When an error occurs within the Try block, the error is first saved to the $Error automatic variable and then searches for a Catch block to handle the error.

If a matching Catch block not found, PowerShell continues to search for an appropriate Catch block or Trap statement in the parent scopes.

After a Catch block is completed or no Catch block or Trap statement is found, the Finally block is run.

A Try statement contains a Try block, zero or more Catch blocks, and zero or one Finally block.

A Try statement must have at least one Catch block or one Finally block.

Syntax :

try { 
< statement list > 
catch [ [< error type >][',' < error type >]* ] 
< statement list >
finally {
< statement list >

Example :

$ErrorActionPreference = "Stop"
   Set-Location $HOMEDesktop
   Get-Content hello.txt
   Write-Output "Could not find the file"
Write-Output "Task completed"

Output : 

Could not find the file
Task completed