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.

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
    $Err[0].Exception
}

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.

You can always use try and catch with PowerShell

    try
    {

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


    catch [System.Management.Automation.ActionPreferenceStopException]
    {

    }
  • thanks for the example.Could you please mention some articles for detailed study – V.B Oct 18 '12 at 11:44
  • 1
    Here is one of good resource: jyothiregode.wordpress.com/2011/02/12/… – 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

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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