Handling errors with PowerShell try-catch command

Have you ever seen an application crash? If so, you know how frustrating it can get and if you’re a programmer, you’ll probably be cursing the developer for not putting in the right error handling mechanism in it! And that’s exactly what this piece is all about. Error handling is an integral part of an application’s code as it catches unforeseen errors and ensures that the application is terminated safely. As with most programming languages, PowerShell also supports an error handling mechanism called try-catch, but before that, let’s learn a bit about error handling in PowerShell.

Why do you need error handling?

exchange errors

A pretty basic question that most of you may already know. Still, let’s briefly touch on it to reiterate some important points.

Error handling helps in the following ways.

  • Prevents an application from crashing.
  • Makes it easy for the user to know that something is wrong and that they should contact the support team.
  • Provides details about the error and its possible causes.
  • Helps with further analysis and to fix the problems.
  • Gives the option to customize the error messages sent to end-users.
  • Makes it easy to maintain your code.
  • Your program could continue to work even after the error, depending on the error and your code.
  • Considered to be a good programming practice.

Now that we’ve touched on the benefits of error handling, let’s see how it can be implemented in PowerShell.

Error handling in PowerShell

502 error

Broadly speaking, there are two types of errors and they are: terminating and non-terminating errors.

Terminating and non-terminating errors

As the name suggests, terminating errors are those that are critical and terminate the program abruptly while non-terminating errors allow the program to run but can give the wrong output or sometimes, even drastic results. Now if you’re wondering, non-terminating errors are potentially more dangerous than terminating errors because you don’t know what aspects can get modified.

Some possible terminating errors are out of memory and syntax errors while the large part of errors in programming logic and unexpected errors fall in the non-terminating category.

Converting non-terminating errors to terminating errors

As a programmer, you can tell PowerShell to treat the non-terminating errors as terminating errors, so the program stops if it encounters that particular error. This change helps you to handle the error using the PowerShell try-catch block because by default non-terminating errors can’t be handled with the try-catch block.

To convert non-terminating errors into terminating errors, use a parameter called ErrorAction. Every cmdlet supports this parameter and it is designed to tell the program what action it should take when it encounters an error. ErrorAction comes with the following options

  • Stop: This stops the program and treats it as a terminating error.
  • Continue: Allows the program to continue and the error is displayed.
  • SilentlyContinue: The program runs and no errors are displayed.
  • Ignore: Ignores the error and continues.
  • Inquire: Displays the error and checks if it should continue.
  • Suspend: This can be used in a Windows PowerShell workflow. The limitation is that it can’t suspend advanced functions.

The syntax for ErrorAction is:

$variable = Get:content \user.txt:ErrorAction Stop

This command changes a non-terminating error into a terminating one, so you can handle it.

Building a try-catch block

Once you have a terminating error or have converted a non-terminating one to a terminating error, you can handle it using PowerShell try-catch block.

The generic syntax is:

try
{
Do some action
}
catch
{
If there is an error, handle it this way
}
For example,
try
{
$variable = Get:content \user.txt:ErrorAction Stop
}
catch
{
write:output "File not found."
}

In this example, data from the file is stored in $variable and if there is an error, the code gets to the catch block and displays the message. The above example is a basic one, designed to give you an idea of the syntax and use. In the real world though, you will use this PowerShell try-catch block to get insights about the error and take action accordingly.

Practical applications of PowerShell try-catch block

powershell function
Shutterstock

You can access the error record inside the catch block. In fact, the error message is stored in the current variable $_. You can do anything with this error record such as parse the error, display a warning, and more. A powerful attribute of the current variable is the Exception as the idea is to know more about the unexpected events that caused the program to stop. Also, Exception itself comes with many attributes like ItemName, GetType, Message, etc.,

For example:

try
{
$variable = Get:content \user.txt:ErrorAction Stop
}
catch
{
write:output $_Exception.Message
}

Now that the basics are clear, let’s move to the advanced part.

You can use the catch block to catch specific exceptions, provided you know or anticipate them. For example, let’s say you want a specific message to be displayed if the file is not found and other messages for other exceptions, your code should look like this:

try
{
$variable = Get:content \user.txt:ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException]
{
write:output "File not found."
}
catch
{
write:output $_Exception.Message
}

Some points to consider when using try-catch

Keep in mind the following points while using the PowerShell try-catch block.

  • There should be no code between the terminating braces of the try block and the catch command. In other words, the word “catch” should immediately be in the next line after the closing braces of the try block
  • This PowerShell try-catch block is most useful to handle errors that you anticipate can happen in the program.
  • The catch block will catch any exception thrown inside the try block regardless of its origin.
  • PowerShell try-catch command is a convenient alternative to multiple if statements.
  • The try block can be followed by any number of catch blocks, but they should be consecutive with no other code in-between.

Finally block

There is something called a finally block that you can use with try-catch. This is an optional one and doesn’t have to be used at all times. This block will execute the code mentioned inside it regardless of whether there was an error or not. This block should come right after the closing braces of the last catch block.

For example:

try
{
$variable = Get:content \user.txt:ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException]
{
write:output "File not found."
}
catch
{
write:output $_Exception.Message
}
finally
{
"An attempt was made to access the user file at Get:Date" | out:file \logfile.log:append
}

In the above example, an entry will be appended in the log file every time an attempt is made to access the file, regardless of whether the file was found or not.

Try-catch: Try it out and avert crashes

Error handling is an important part of any program as it prevents the application from crashing and helps you to analyze the possible cause of the error. PowerShell try-catch block is a powerful way to capture terminating errors, so you can handle them safely without causing a crash. It helps with the detailed analysis and an understanding of the problem as well. For these reasons, it is a must-have in your PowerShell scripts.

About The Author

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top