SharePoint Pals
 | Sign In
How to Use Try Catch Finally and Error Handling in PowerShell
by Sathish Nadarajan 27 Dec 2013
SharePoint MVP
Today  :   3     Total  :    24349

All of us know that as long as we are into SharePoint 2013, we will be in need to write PowerShell scripts then and there. For small scripts, we will be writing in a traditional manner. But when we plan to write a bigger one, with some complex logics and all, then we require Try Catch Finally block for sure. Here I am NOT planning to explain about the Try Catch Finally block. But, let us have a look, how to use them in PowerShell.

A general syntax, which everyone would have come across in PowerShell world is

 -ErrorAction SilentlyContinue

This is the one which is an important enemy to the Try Catch in PowerShell. Because, when this particular statement got executed, then the exception will not be caught. It will proceed SILENTLY. In some of the scenarios we may require this.  I agree with that. But in most cases, we require our exception to be caught.

To make our exceptions to be caught in the catch block, we need to specify it explicitly by executing the below statement at the beginning of our script.

 $ErrorActionPreference = "Stop"

Then the remaining code would be the same. For example, let us have a look, how a particular script will looks like with proper Try Catch and Finally Blocks.

 $ErrorActionPreference = "Stop"
     Write-Host "Adding PowerShell Snap-in" -ForegroundColor Green
     # Try to get the PowerShell Snappin.  If not, then adding the PowerShell snappin on the Catch Block
     Get-PSSnapin "Microsoft.SharePoint.PowerShell" 
     if($Error[0].Exception.Message.Contains("No Windows PowerShell snap-ins matching the pattern 'Microsoft.SharePoint.PowerShell' were found"))
         Add-PSSnapin "Microsoft.SharePoint.PowerShell"
 Write-Host "Finished Adding PowerShell Snap-in" -ForegroundColor Green 

If I didn’t give the Statement ErrorActionPreference, then the catch block will never get executed.

The ENUM values for the above mentioned parameter are

1. Continue

2. Ignore

3. Inquire

4. SilentlyContinue

5. Stop

I don’t think there is much explanation required as we can get what exactly they will do by looking on the terms itself.

With the above understanding, let us see a little bit deep into the exception types on PowerShell scripting.

Basically the Errors are classified as 2 types on PowerShell.

1. Terminating Errors

2. Non-Terminating Errors

Terminating Errors

They are the errors which will be caught by the default catch block, without doing anything extra. That is, there is no need of explicitly set the ErrorActionPreference Parameter for these type of errors.

Non-Terminating Errors

Usually, these type of errors, will not be caught by the catch block. For example,

 $ConfigXmlPath = "C:\Sathish\Config. xml"
 # Get the Content of the Config Xml
  [Xml]$SiteConfig = Get-Content $ConfigXmlPath  

In the above line, I am trying to read the content of the Config File. If the config file, doesn’t present, ,this will not be caught in catch by default unless until, we choose Stop Action.

Switching between Terminating and Non Terminating

Actually, we can make any kind of statement into a terminating and a non-terminating one by using the –ErrorAction Switch. Let us take the above script itself for our example. The above script is a Non-Terminating type as I mentioned. To make it as terminating, we can give

[Xml]$SiteConfig = Get-Content $ConfigXmlPath -ErrorAction Stop

Now, this statement will caught by the Catch block.

Let us try to make everything as a Terminating Exception. That is what absolutely required for every developer. We need all the exceptions should be caught. To make that, always place the below piece on top of all the scripts which we are writing.

 $ErrorActionPreference = "Stop"

Handling the Catch Block:

Now, we saw how to catch our exceptions. Now, we need to know, how to handle those exceptions, and we should respond for the exceptions right.

     if($Error[0].Exception.Message.Contains("No Windows PowerShell snap-ins matching the pattern 'Microsoft.SharePoint.PowerShell' were found"))
         Add-PSSnapin "Microsoft.SharePoint.PowerShell"

On the above example, I am verifying, the Exception Message. By default, the $Error is a variable, which will hold all our errors. Out of that, the array of 0 is nothing but the latest exception happened. Then the exception class as usual we know about them.

In the same manner, we can catch our exceptions with

         $ErrorMessage = $_.Exception.Message
     $FailedItem = $_.Exception.ItemName




Finally we came to the Finally Block :) .  This as usual with any other programming language, will get executed, irrespective of try or catch block.  Usually, we will be using this finally to dispose our objects.



Happy Coding.

Sathish Nadarajan.

blog comments powered by Disqus

SharePoint Pals

SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile


Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community

SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation