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.
2 Answers
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.BOct 18, 2012 at 11:44
-
1Here is one of good resource: jyothiregode.wordpress.com/2011/02/12/… Oct 18, 2012 at 12:13
-
thanks for the link though but it tells more about cmdlets than exception handling.– V.BOct 19, 2012 at 4:52