SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am very new to writing PS scripts for deploying solutions and activating features. In my current scripts I get errors some time like feature not activated or deactivated properly. I am looking forward to introduce exception handling in my scripts. I want to display some custom messages and move on with rest of the commands.Please point me to some good resources/articles.

share|improve this question
up vote 1 down vote accepted

The answer is, that it depends...

If you are running some general provisioning script, you quite often want the script to stop dead in its tracks if an error continues, preferably with an explanation of why the error occurred.

In that case either specify -ErrorAction Stop on the cmdlet or set $ErrorActionPreference = "Stop" to set it for the whole shell process.

If you want to act on a given error, you can set -ErrorAction "SilentlyContinue" (or -EA 0) and set -ErrorVariable Err (or -EA) that you check after the cmdlet has run.

Enable-SPFeature -Identity <guid> -Url <url> -EA 0 -EV Err

if ( $Err )
    # feature enabling failed 
    # here you could either write out error or log and continue if appropriate

As Falak mentions, you also have try/catch/finally. You shouldnt really use those to control flow of your functions, but they do have good valid uses as long as they are specific in what error they catch and how they handle it (rethrow or log). I would not recommend however to have "blind" catch statements that does nothing but swallow exceptions. That is a bad code practice as it hides the problems without addressing it.

share|improve this answer

You can always use try and catch with PowerShell


        Enable-SPFeature -Identity "00bfea71-c796-4402-9f2f-0eb9a6e71b18" -Url http://yoursite/yourweb -ErrorAction Stop

    catch [System.Management.Automation.ActionPreferenceStopException]

share|improve this answer
thanks for the example.Could you please mention some articles for detailed study – V.B Oct 18 '12 at 11:44
Here is one of good resource:… – Falak Mahmood Oct 18 '12 at 12:13
thanks for the link though but it tells more about cmdlets than exception handling. – V.B Oct 19 '12 at 4:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.