An error in a PowerShell script will prevent it from completing successfully. Using error handling with try catch blocks allow for managing and responding to these terminating errors. In this post I will cover the basics of try/catch blocks and how to find and handle specific exception messages.

Understanding the Syntax

The try catch block syntax is very simple. It is composed of two sections enclosed in curly brackets with the first identified as the try block and the second as the catch block.

try {
    # Statement to try
}
catch {
    # What to do with terminating errors
}

The try block can have as many statements in it as I want; however, I would recommend keeping it to as few as possible, probably just a single statement. The point of error handling is to work with one statement at a time and deal with anything that occurs with it.

Here is an example of an error occurring in the PowerShell console. Here I am creating a new file using the New-Item cmdlet and specifying a non-existent folder for Path:

If this was in a script, outputting this to the screen would waste some space and the problem may not be immediately visible. Using a try catch block, I can start to manipulate the error output and make it more admin friendly.

Here is our same New-Item command in a try catch block. Note that on line 2 I had to add the ErrorAction parameter with a value of Stop to the command. Not all errors are considered “terminating”, so sometimes I need to add this bit of code in order to properly terminate into the catch block.

Basic try/catch block

Now instead of a block of red angry-looking text, I have a simple warning message that it ran into an issue. The non-existent Path name along with forcing -ErrorAction Stop drops the logic into the catch block and display my custom warning.

Using the $Error Variable

While more readable, this is not very helpful. All I know is the command did not complete successfully but I don’t know why. Instead of displaying my custom message, I can display the specific error message that occurred instead of the entire red text exception block. When an error occurs in the try block, it is saved to the variable named $Error. The $Error variable contains an array of recent errors, and I can reference the most recent error in the array at index 0.

Try/catch block using $Error variable

The warning output is now more descriptive showing that the command failed because it couldn’t find part of the path. This message was a part of our original error message but is now more concise.

Using Exception Messages

I can also use multiple catch blocks in case I want to handle specific errors differently. Here I’m going to display two different custom messages, one for if the path does not exist and one for if an illegal character is used in the name. Note that in the following screenshot I ran the script twice with two different commands in the try block. Each command, catch block, and final output are indicated by the orange and green arrows.

Try with multiple catch statements

Looking at lines 14-16, there is a third catch block without an exception message. This is a “catch-all” catch block that will run if the error does not match any other catch block exception. If I’m running this script and see the message in the last catch block, then I know the error is not related to an illegal character in the file name or part of the path not being valid.

Now how did I know the exception messages to use in the first two catch blocks? This can be found by looking at the different information attached to the $Error variable. After a failed command occurs, I can run $Error[0].Exception.GetType().FullName to view the exception message for the last error that occurred.

Going back to the PowerShell console, I reran the New-Item command with a non-existent path, then ran my $Error command to find the exception message.

The red text immediately following the failed command also contains the exception message but does not contain which module it is from. Looking at the $Error variable shows the full message to be used for a catch block.

Using try/catch blocks gives additional power in handling errors in a script and taking different actions based on the error. The catch block can display more than just an error message. It can contain logic that will resolve the error and continue executing the rest of the script.

Do you have any tips on using try/catch blocks? Leave a comment below or find me on Twitter or LinkedIn for additional discussion.

References:

Microsoft Docs: About Try Catch Finally
Microsoft Docs: About Automatic Variables ($Error)
Microsoft Blog: Understanding Non-Terminating Errors in PowerShell

Leave a Reply