7

I´m searching for the best way to handling exceptions in PowerShell. In the following example I want to create a new SharePoint web and remove a old SharePoint web. When the New-SPWeb fails, it is necessary that the script ends. I think try/catch is the best way, because the "if" statement only checks if $a exists. Are there still other options to handling exceptions?

Exception handling with "if" statement:

$a = New-SPWeb http://newspweb
if($a -eq $null)
{
Write-Error "Error!"
Exit
}
Write-Host "No Error!"
Remove-SPWeb http://oldspweb

With try/catch:

try
{
$a = New-SPWeb http://newspweb
}
catch
{
Write-Error "Error!"
Exit
}
Write-Host "No Error!"
Remove-SPWeb http://oldspweb
2
  • 1
    DON'T ever again use the term "if loop" or be prepared to have your developer status questioned. - SCNR Commented May 18, 2012 at 10:42
  • Sure a if statement is not a loop :-) I fixed it Commented May 18, 2012 at 19:25

2 Answers 2

10

Try/catch is really for handling terminating errors and continuing on. It sounds like you want to stop on a non-terminating error. If that's the case, use the ErrorAction parameter on New-SPWeb and set it to Stop e.g.:

$a = New-SPWeb http://newspweb -ErrorAction Stop

This will convert the non-terminating error into a terminating error.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Keith. This paramter is really helpfull!
This parameter is one of several "common" parameters found on all cmdlets. Check out the associated help topic man about_CommonParameters.
Keith, I think you mean non-terminating errors. Terminating errors will stop anyway. :)
@JasonMArcher, OK misread your comment at first - yes, that was what I meant. Thanks for pointing that out.
5

Try catch is certainly the right way. But, it will catch only terminating errors. So, if New-SPWeb does not throw a terminating error, you can never catch it. I guess, it results in a terminating error.

BTW, if you want all details about the error, output $_ in catch {}. It will have all error information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.