Exceptions in PowerShell

When scripting anything in PowerShell, you might find out that the exception handling in PowerShell V2 is not very extensive. I ran into a problem using the “New-SPSite” cmdlet for SharePoint 2010. The solution that I used for my problem can also be used for any other Cmdlet.

Running this cmdlet when the site collection does not yet exist, would give no problems. If a site collection already exists, and you try to create a new site collection using the same URL, you get a “not so user friendly” error.

The script I was creating was not just creating a site collection, so I would like to see just a message saying “The site collection could not be created.”.

Since I am still a PowerShell beginner, I was trying to find a way to accomplish this.
The first thing that came in mind, and I had used successfully before, was using Try{} Catch{] to see if a command executed correctly. In this case however, the command is execution just fine, but the result is not what you would want, so the Try{} Catch{} was not a solution.

To resolve this issue, I used the following “check” to see if the command had executed correctly, using an if statement.

#Check if the command I ran was executed correctly
if([bool](New-SPSite “http://yourdomain.com” –OwnerAlias “SA\Administrator” –ErrorAction SilentlyContinue) –Eq $false){Write-Host “The site collection could not be created” –fore red}

The parameter –ErrorAction SilentlyContinue suppresses the actual error, so the result will be clean. The suppressing of the error will only happen for this New-SPSite cmdlet, so it will not affect the rest of your script.
If you want to suppress ALL error messages (I don’t see a reason why anyone would want this), you can change the $ErrorActionPreference variable. The default value is “Continue”. Change the value to “SilentlyContinue” to suppress error messages in your PowerShell session.

$ErrorActionPreference = “SilentlyContinue”