Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - Exception handling

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
like image 523
LaPhi Avatar asked Mar 21 '11 13:03

LaPhi


2 Answers

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.

like image 120
Keith Hill Avatar answered Sep 25 '22 02:09

Keith Hill


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.

like image 21
ravikanth Avatar answered Sep 22 '22 02:09

ravikanth