Powershell

How to Use try-catch in PowerShell

Errors are confusing and stressful for all computer users; they are frequently challenging to read, making you wonder where the script went wrong. It is also possible that a script that is executed once will not run again. There can be any problem that arises when you are least expecting it. That is why you should include error handling in every PowerShell script you write.

PowerShell has some excellent options for dealing with errors. Even in the most straightforward script, it can manage errors while ensuring that an unexpected event does not cause a system crash. By implementing the concept of error handling, errors can be filtered and shown to make them easier to understand, adding extra logic to the error management process. Try and catch blocks are utilized to handle or respond to the terminating errors in PowerShell scripts. 

What is a try-catch Block in PowerShell

We will answer this question in this section:

A “try” block is used to specify a part of a script where PowerShell should look for issues. The $Error automatic variable first stores the error in itself when the try block encounters an error. After that, PowerShell looks for a catch block for handling the error. PowerShell searches the parent scopes for a suitable catch block if the “try” statement does not have a paired catch block. The “finally” block is executed after the catch block, or if no appropriate catch block has been found. The error is written to the error stream if it cannot be handled.

A “catch” block comprises commands for monitoring the error or restoring the script’s expected flow. The types of errors that a catch block will catch can be specified. Various types of errors are included in a try statement, and multiple catch blocks are then utilized to handle those errors.

A “finally” block is utilized to free up or release any resources that your script no longer requires.

Syntax of try-catch and finally in PowerShell

A Try statement is composed of a try block, with one or more “catch” and “finally” blocks. You should have at least one “catch” or “finally” block with every try statement in your script. A statement list enclosed in brackets follows the try keyword.

try {<statement list>}

The script sends the error object from the try block to its paired catch block if a terminating error occurs while the statements in the statement list are executing. Error types are placed within brackets, and the outermost brackets indicate the element’s optionality.

The catch block has a statement list and an optional list for error type definitions. PowerShell looks for the suitable catch block if a terminating error occurs in the try block. In case if the paired try-catch block is found, the program will execute the catch block statements.

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

You can specify one or more types of errors in the catch block. These errors are the .NET exception. A catch block works with exceptions from the specified .NET Framework exception class and other derived classes.

If an error type is specified in a catch block, then it is the responsibility of the same catch block to handle that error. If an error type is not defined in the catch block, it will handle any error that the try block encounters. A try statement can have numerous catch blocks to handle various error kinds. The Finally keyword comprises a statement list that runs every time the script is executed, whether the Try block executes without error or if an error exists in a catch statement.

finally {<statement list>}

Executing Single try-catch in PowerShell Script

Now, we will check out the practical implementation of the try-catch method. Firstly, open your Windows PowerShell ISE and create a new file:

Write out the following code in this file and save this PowerShell script named “testfile2.ps1”; you can name it as you want.

try { NonsenseString }
catch { "An error occurred." }

PowerShell does not recognize the “NonsenseString” as any object or command, so the catch statement will be executed after running the script:

Executing Multiple try-catch in PowerShell

Any number of catch blocks can be used with a try statement. In the below-given example, we added a try block that download “MyDoc.doc” and has two catch blocks:

The first catch block will deal with System.IO.IOException and System.Net.WebException sorts of errors. The error type in the second catch block is not provided. This block is also responsible for handling any other termination errors.

try {
   $wc = new-object System.Net.WebClient
   $wc.DownloadFile("http://www.contoso.com/MyDoc.doc","E:\download\testfile.doc")
Write-Host “File has downloaded successfully !
}
catch [System.Net.WebException],[System.IO.IOException] {
    "Unable to download MyDoc.doc from http://www.contoso.com."
}
catch {
    "An error occurred that could not be resolved."
}

Save the code and execute it.

The output declares that the “MyDoc.doc” file is successfully downloaded into the “E:\download” folder:

To verify the existence of the newly downloaded “MyDoc.doc” file, we will utilize the “Get-ChildItem” command. This command will extract all the child items of the “E:\download” folder:

> Get-ChildItem “E:\download”

PowerShell uses inheritance to match error kinds. A catch block is used in the below-given example to catch a “Command Not Found” error:

catch [System.Management.Automation.CommandNotFoundException]
{"Inherited Exception" }

Here, we have the exception.

Extract Exception Information in PowerShell

The current error can be obtained via $_, also known as $PSItem, within a catch block. The object is of the “ErrorRecord type,” and it contains information about the encountered error.

 try { NonsenseString }
catch {
  Write-Host "An error occurred:"
  Write-Host $_
}

There you have it!

Conclusion

PowerShell try-catch blocks allow you to handle script problems and perform various operations depending on the encountered errors. Not only the error message can be displayed in the catch block, but it may also include logic for handling the error and continuing to run the remaining script.

In this article, we have provided you with different methods of using try-catch in PowerShell. These methods include executing single try-catch, multiple try-catch statements, and extraction of exception information in PowerShell.

About the author

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.