PowerShell Try Catch Finally Error Handling

I’ve recently been experimenting with the script blocks in PowerShell try catch finally.  These script blocks can help you deal with terminating errors that may occur in your scripts.  A terminating error, otherwise known as an exception, will stop a command from processing the current object or from processing additional objects.  On the other hand, there are many situations that will result in a non-terminating error.  In a non-terminating error situation an error will generally be displayed on the console and continue processing.  An example of a non-terminating error is passing a variable containing a list of mailboxes to the Get-Mailbox cmdlet.  If an error occurs matching a name in the variable to an Exchange mailbox, the process continues but an error is displayed to the console.  A good resource for determining what exactly constitutes a terminating error or non-terminating error can be found in this MSDN article. This is where the script blocks try catch finally can be helpful. The try block is where you will put the code that you want to execute and monitor for errors.  If an error occurs then the code in the catch block is executed.  It is possible to include multiple catch blocks in order to catch certain types of errors.  The finally block runs no matter what happens during the try and catch script blocks.  The finally block can be used to provide informational output gather from a script or free up resources, per Microsoft’s documentation.  You may even choose to omit the finally block as part of your script if you don’t feel that it is necessary.

So if you are using the try catch finally blocks and have non-terminating errors within the try block, the catch block ignores the errors and does not fire.  It is possible to force any error in the try block by using the -ErrorAction switch.  Setting the error action to stop forces the catch block to see all errors, either terminating or non-terminating.

You’ll notice in the catch block that I’m using the $Error variable. This is where PowerShell stores all the errors for a given session.  Using [0] after the $Error variable denotes accessing the first time in a PowerShell array so we’ll be returning the most recent error in $Error.  Just for the sake of the example, the finally block unloads the Exchange 2010 PowerShell snapin.

Ok so this script is reinventing the wheel a bit but the try catch finally script blocks are extremely useful for handling terminating errors or when you want to trap non-terminating errors in your code.

1 thought on “PowerShell Try Catch Finally Error Handling

Leave a Reply