PowerShell - exception handling

I am looking for a better way to handle exceptions in PowerShell. In the following example, I want to create a new SharePoint website and delete the old SharePoint website. When the New-SPWeb crashes, it is necessary for the script to complete. I think try / catch is the best way because the if statement only checks if $ a exists. Are there other options for handling exceptions?

Handling exceptions using the 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 
+7
source share
2 answers

Try / catch is really designed to handle trailing errors and continue. It looks like you want to dwell on an error that does not end there. In this case, use the ErrorAction parameter on New-SPWeb and set it to Stop for example:

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

This will convert an irreversible error to a final error.

+10
source

Try to catch, of course, the right way. But he will catch only the final errors. So, if New-SPWeb does not throw a final error, you can never catch it. I assume this leads to a final error.

BTW, if you want detailed error information, print $_ in catch {}. He will have all the error information.

+5
source

All Articles