powershell try catch

While working on any new PowerShell script, it is always a good idea to include a Try Catch mechanism for error handling.

It may take some additional time, but it will help you prevent the application from crashing.

Powershell Try Catch block is a mechanism used to handle terminating errors in PowerShell scripting.

There are two types of errors:

  1. Terminating
  2. Non-terminating errors

Terminating errors will stop/halt the script from further execution, while a non-terminating error will not stop the execution and can give the wrong output.

Non-terminating errors are more dangerous than terminating errors because you don’t what happened after executing the script. There is No Error Message or Log to warn you.

Some good examples of terminating errors are memory and syntax errors, whereas unexpected errors and errors in programming logic come from non-terminating errors.

Error handling mechanism will help in the following ways:

  • Used to prevent an application from crashing.
  • You can find detail information and cause of the error.
  • Easily maintain your code.
  • You can run your script continuously even after the error.
  • Allow you to customize the error messages.

In this tutorial, we will learn how to use Try Cache to establish error handling in PowerShell scrip.

Basic Syntax of PowerShell Try Cache

The basic syntax of the PowerShell Try Cache is shown below:

try
{
statement list
}
catch(error)
{
statement list
}
finally
{
statement list
}

A brief explanation of each syntax is shown below:

  • try
    “try” is a PowerShell block that you want PowerShell to monitor for errors. When any error occurs during the script execution, it will immediately stop at that point and move onto the Catch block if the error is a terminating error.
  • catch
    This is the place where the execution of code continues after an error occurs within the Try statement. It is used to handle the errors generated in the try block.
  • finally
    It is executed after both the Try and Catch blocks whether an error occurred or not. This is an optional block and primarily used to free up any resources that are not required by the script.

The Try, Catch, and Finally statements are used for controlling the script flow when you encounter any errors.

Converting Non-Terminating Errors to Terminating Errors

PowerShell is a very expressive language compared to other programming languages.

Only a single line PowerShell code can perform thousands of raw CPU instructions.

Sometimes the executed code may succeed while other times it may fail.

This is where the concept of a Non-Terminating error comes into the picture.

A Non-Terminating error does not prevent the command from moving on and trying the next item on a list of inputs, while a Terminating error causes the entire command pipeline to fail.

When writing a new script, it is a good idea to treat the non-terminating errors as terminating errors so the script stops if it gets any errors during execution.

By default, the try-catch block can not handle the non-terminating errors. So you will need to convert the non-terminating errors into terminating errors using the parameter ErrorAction.

ErrorAction tells the Powershell script or program what action it should take when it encounters an error.

You can use the following options with ErrorAction:

  • Stop
    Is used to stop the program and treats it as a terminating error.
  • Continue
    Is used to run a program continuously and display errors.
  • SilentlyContinue
    The program runs continuously without displaying any error.
  • Ignore
    Is used to Ignore Any Error and Runs Continuously.
  • Inquire
    Is used to Display the Error and Checks if it should continue.

The basic syntax of ErrorAction is shown below:

$variable = Get:content C:\file.txt:ErrorAction Stop

To understand this better, let’s see the following example:

try
{
Perform some action
}
catch
{
If any error, handle it this way
}
For example,
try
{
$variable = Get:content C:\file.txt:ErrorAction Stop
}
catch
{
write:output "Your specified file not found."
}

In the above example, data from the given file is stored in the variable $variable and if there’s an error, the code gets to the catch block and displays the error message.

Treating All Errors as Terminating

You can also treat all errors as terminating using the ErrorActionPreference variable.

If you want to include it with the script at the following lines at the top of the script:

$ErrorActionPreference = Stop

If you want to set it in the PowerShell session, run the following command in the PowerShell console:

$ErrorActionPreference = Stop

Catching a Terminating Error

Next, you will need to create a Try Catch block around the command that causes the error.

Then, you should place a Catch block to handle the error.

This catch block is only accessed once any terminating errors occur.

The whole code should be as shown below:

Try
{
$variable = Get:content C:\file.txt:ErrorAction Stop
}
Catch
{
write:output "Your specified file not found."
}

Accessing The Error Record

Try Catch also allows you to access the error record. Generally, all error records are stored in the $_.Exception variable.

It contains very useful information about the error.

Let’s see the following example:

Try
{
$variable = Get:content C:\file.txt:ErrorAction Stop
}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
write:output "Failed to read file $FailedItem with message $ErrorMessage"
}

Use Try Catch Finally

The Finally block is the last part of the Try Catch. You can define it after the Catch block and runs every time.

It is very useful when you need to close the resources you opened.

Let’s see the following example:

Try
{
$variable = Get:content C:\file.txt:ErrorAction Stop
}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
write:output "Failed to read file $FailedItem with message $ErrorMessage"
}
Finally
{
$Time=Get-Date
"This script made a read attempt at $Time" | out-file c:\logs\ExpensesScript.log -append
}

In the above script, we are going to log that a file once read was attempted.

Conclusion

In the above tutorial, we learned how to handle error in PowerShell script with Try Catch.

It is recommended that you write a PowerShell script with Try Catch mechanism so you can easily troubleshoot and fix errors as they come up.

Hopefully you now have the knowledge needed to write your own PowerShell script with Try Catch.

Feel free to ask any questions in the comments section below.

Leave a Reply

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