Powershell Try Catch Finally and Error Handling

-

|

Introduction

Powershell Try Catch blocks are used to handle terminating errors in PowerShell scripting. When use Powershell Try Catch block for scripting you can achieve the following:

  1. Get your script to continuing running despite a terminating error
  2. Display and handle error messages better

In this guide you will learn how to use Powershell Try Catch blocks to handle terminating error messages in PowerShell.

Advertisement

Powershell Try Catch Syntax

Below is the syntax of Powershell Try Catch

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

try is the part of the block you want PowerShell to monitor for errors. This is the block with the original scripts that may return a terminating error. When an error occurs here, PowerShell saves the error in the $Error automatcic variable (more on this later).

catch statement handles the errors generated in the try block. You can also specify the types of errors that is handled in the catch statement.

finally block may be used to free up any resources that are no longer needed by the script.

If an error occurs in the try block, the error is saved in $Error variable. Then PowerShell will search for a catch block to determine how to handle the error message. You can have multiple catch statements in a Try Catch statement.

Types of Errors in Powershell Try Catch

Within the catch block of Try Catch, you can specify the type of error message you want to handle. Here is how you specify the error exception type:

try {

}
catch [System.InvalidOperationException] {

}

In the example above the error message you want to handle is System.InvalidOperationException.

I said earlier that error messages in the try block are saved in the $Error variable. To determine the type of error, run the command in the try block, then run the following commands.

$error[0].exception.gettype().fullname 

As a quick example, I will run this command below:

try {
Get-EventLog -LogName Systerr -ErrorAction SilentlyContinue
}
Catch {
}
I know the command will throw an error message because there is no event log called Systerr.

When I run the script, it appears that there is no error message because I used SilentlyContinue for ErrorAction.

C:\G-Drive\Work Tools\Products Portal\1. New Business\2. Content Sites\1. iTechGuides.com\Posts\Windows OS\Command Line Tools\PowerShell\Powershell Try Catch\images\powershell try catch example 0,0.png

But when I run

$error[0].exception.gettype().fullname 

The type of error is shown (highlighted below)

I can then add this error type in my catch block

try {

}
catch [System.InvalidOperationException] {

}

Specifying a particular error type may come with a problem. Your script may not be able to handle other types of errors.

As an example, run the command below:

try {
Get-EventLog -LogName System -ComputerName tets -ErrorAction SilentlyContinue
}
Catch [System.InvalidOperationException] {

}

My script did not handle the error message. See the result below:

Why? Because it is a different type of error. If you look at the command, I have the correct event log name, System but I am trying to connect to a remote computer tets that does not exist.

To determine the type of this new error, run the command below:

$error[0].exception.gettype().fullname

Boom! We have our error exception type, System.IO.IOException.

I can then include this error type into the catch block so that my script can also handle the error message thrown by this type of exception.

Here is the modified script (modified to throw both errors)

try {
Get-EventLog -LogName Syst -ComputerName tets -ErrorAction SilentlyContinue
}
Catch [System.InvalidOperationException], [System.IO.IOException] {

}

How to Add multiple Catch Blocks in PowerShell Try Catch Statement

You can add multiple catch blocks in a PowerShell Try Catch statement. This way you can determine the type of exception that each catch block can handle.

Continuing with the previous example, here is the modified version of the script with two catch blocks.

 try {
Get-EventLog -LogName Syst -ComputerName tets -ErrorAction SilentlyContinue
}
Catch [System.InvalidOperationException], [System.IO.IOException] {

}
Catch {

}

In this example, the first catch block will handle the specified types of exceptions. The second one will handle generic errors.

How to Include Finally Block to PowerShell Try Catch Statement

You can include a Finally block to PowerShell Try Catch Statement.

The syntax is

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

The finally block may be used to free up any resources that are no longer needed by the script.

A Finally block runs even if you use CTRL+C to stop the script. The block will also run if an Exit keyword stops the script from within a Catch block.

Other Ways to Capture Errors With PowerShell Try Catch

So far you already know that error messages are saved in the $error variable. There is also another variable, $_ that stores error messages. $_ is knows as $PSItem. You can display errors stored in $_ variable.

Furthermore, the $error variable has other properties you can explore. To determine other possible ways to display errors with $error variable, run the command below:

$error | Get-Member

The command returned the following:

Some important properties you can explore are:

Exception, ErrorDetails and ScriptStackTrace

To access one any of these properties, enter $error, followed by a dot. Then the name of the property. For example, to see the ErrorDetails, use the command below:

$error.ErrorDetails
Advertisement

Conclusion

If you want to go pro in your PowerShell scripting, you need to use PowerShell Try Catch statement blocks. Without this, your scripts may throw errors that may not be easily understood or even stop entirely.

I hope this guide simplified PowerShell Try Catch for you. I also hope that you now have a better understanding of PowerShell error hadling.

If you have any question use the “Leave a Reply” form at the end of this page. Alternatively, share your experience handling errors in PowerShell.

Other Helpful Guides

Additional Resources and References

LEAVE A REPLY

Please enter your comment!
Please enter your name here

FEATURED POSTS

How to Share a Folder in Windows 10 (3 Methods)

Introduction This guide demos how to share folder in windows 10. It covers 3 methods. Options...

How to Map Network Drive in Windows 10 (5 Methods)

Introduction This guide demos 5 methods to Map Network Drive in Windows 10. Options to...
How to Install Windows 10 1909 Preview Build

How to Install Windows 10 19H2 Preview Build

Introduction If you are a member of Windows 10 Insider Program you can install Windows 10 19H2 Preview Build....

How to Sign in to Windows 10 with a Microsoft Account

Introduction When you installed Windows 10 you may have created and signed in with a local account. You can...
Disable IPv6 in Windows 10

How to Disable IPv6 in Windows 10 (3 Methods)

Introduction This guide demos 3 methods to disable IPv6 in Windows 10: Disable IPv6 from...

Advertisement

TRENDING POSTS

Remote Desktop Connection

Remote Desktop Connection an Internal Error Has Occurred [Fixed]

Introduction I recently received the error message "Remote Desktop Connection an Internal Error Has Occurred". It was strange because...

Find My Samsung: Register and Use Samsung Find my Mobile

Introduction Ever wondered how you could find your Samsung phone if you lost it? Find my Samsung or Samsung...
What is the Difference Between PowerShell and CMD?

Windows Powershell vs CMD: Differences and Similarities

Introduction This short guide compares Windows PowerShell vs CMD (Windows command prompt). I will cover the history and nature...
Spotify No Longer Supports this Version of Microsoft Edge

Spotify No Longer Supports this Version of Microsoft Edge [Fixed]

Introduction When you open Spotify web player on Microsoft Edge, you may receive the error message "Spotify No Longer...
Windows 10 Won't Boot

Windows 10 Won’t Boot With Black Screen? 3 Ways to Fix It

Why Won't Windows 10 Boot Up? If your Windows 10 stops with a black screen, the first question in...

Advertisement

BEST OF ITECHGUIDES

how to change wifi password

How to Change Wifi Password for Any Wifi Router

Introduction To change your Wifi password (PIN), you need the IP address and admin login for the router. Once...
How to Change Profile Picture on Spotify

How to Change Profile Picture on Spotify (from Desktop or Mobile)

Introduction You can change profile picture on Spotify from the desktop or mobile app. This guide covers the steps...
Hotmail email (outlook.live.com)

Hotmail Email (Outlook.com Email): Your Definitive Guide

Introduction I suppose the first question on your mind is, "what happened to Hotmail email?" This is because when...
Windows 7 Support End Date

Windows 7 Support Ends January 14, 2020: Your Upgrade Options

Introduction According to Microsoft, Windows 7 support end date is January 14, 2020. Microsoft recommends that you upgrade to...
DISM.exe /Online /Cleanup-Image /Restorehealth

DISM.exe /Online /Cleanup-Image /Restorehealth Explained

What is DISM.EXE /Online /Cleanup-image /RestoreHealth? "DISM.exe /Online /Cleanup-Image /Restorehealth" is a DISM command that repairs issue with the...

RECENT POSTS

How to Enable Hyper-V in Windows 10 (3 Methods)

How to Enable Hyper-V in Windows 10 (3 Methods)

Introduction This guide demos 3 methods to enable Hyper-V in Windows 10. To install Hyper-V...
RSAT Tools in Windows 10 Explained: Plus How to Install RSAT

RSAT Tools in Windows 10 Explained: Plus How to Install RSAT

Introduction Starting from October 2018 (1809) update, RSAT Tools became part of Windows 10. From this version of Windows...

How to Enable RSAT for Active Directory in Windows 10 (3 Methods)

Introduction This guide demos 3 methods to enable Active Directory in Windows 10. It is not exactly enabling "Active...
How to Install Windows 10 1909 Preview Build

How to Install Windows 10 1909 (19H2) Preview Build

Introduction Windows 10 1909 Preview is available for Windows Insiders. Made available early September, 2019 you have to be...
How to Install RSAT in Windows 10 (3 Methods)

How to Install RSAT in Windows 10 (3 Methods)

Introduction This guide demos how to Install RSAT in Windows 10. Starting with Windows 10...

How to Share a Folder in Windows 10 (3 Methods)

Introduction This guide demos how to share folder in windows 10. It covers 3 methods. Options...
Configure Map Network Drive with Group Policy

Map Network Drive in Windows 10 with Group Policy

Introduction This guide demos how to map network drive with group policy. This guide is...

How to Map Network Drive in Windows 10 (5 Methods)

Introduction This guide demos 5 methods to Map Network Drive in Windows 10. Options to...
How to Download Windows 10 ISO with Media Creation Tool

How to Download Windows 10 ISO with Media Creation Tool

Introduction This guide demos the steps to download Windows 10 ISO. You can download Windows 10 ISO with Media...

How to Install Windows 10 from Network Boot (Via WDS Server)

Introduction This guide demos how to install Windows 10 from network boot. The steps discussed in...

Advertisement

MUST READ

bullet points in excel

4 Easy Ways to Insert Bullet points in Excel

Introduction Inserting bullet points in excel is not as straightforward as adding bullet points in Word. This guide demonstrates...
powershell windows 10

Frequently Asked Powershell Windows 10 Questions

This guide brings the top 8 Frequently asked Powershell Windows 10 questions. Get answers to common Windows 10 PowerShell FAQs…
Windows 10 not booting after update

How to Fix Windows 10 Boot Problem After Windows Update

If you experience Windows 10 not booting after an update, it is likely that the update corrupted the boot files.
ClearScore

ClearScore Can Help Improve Your Credit Score for FREE (Here is How)

What is ClearScore and Who is ClearScore? ClearScore (Some call it Clear Score!) is a London-based financial services company...
windows update 0x8024401c

How to Fix Windows Update Error 0x8024401c in Windows 10

Introduction Received Windows Update 0x8024401c error in Windows 10? You have done this and done that yet, the error...

By using this website you agree to accept our Privacy Policy and Terms & Conditions