How to Use Try Catch Finally and Error Handling in PowerShell

Sathish Nadarajan
 
Solution Architect
December 27, 2013
 
Rate this article
 
Views
43255

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"
 
 try
 {
     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" 
 }
 catch
 {
     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:SathishConfig. 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.

 catch
 {
     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

 catch
 {
         $ErrorMessage = $_.Exception.Message
     $FailedItem = $_.Exception.ItemName
 
 }
 

also.

 

Finally:

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.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment