PowerShell – Exception handling

Question:

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:

With try/catch:

Answer:

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.:

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

Source:

PowerShell – Exception handling by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply