Sharepoint - Powershell and checking for Site existence

Rob, if you check for a site that doesnt exist you will get errors with your approach.

Get-SPWeb "dasdasdasg" # this will throw a non-terminating error

To get past that, you can use several approaches. One is adding the common parameter -ErrorAction (alias is EA) and ErrorVariable (EV).

An example is actually when loading the SharePoint module:

Add-PSSnapin "Microsoft.SharePoint.Powershell" -ErrorAction SilentlyContinue # -EA 0 works also

Use EA carefully, as this swallows your exceptions. Unless you know exactly what exception you are handling, use EA in combination with EV:

$site = Get-SPWeb $siteUrl -ErrorVariable err -ErrorAction SilentlyContinue -AssignmentCollection $assignmentCollection

if ($err)
{
   #do something with error like Write-Error/Write-Warning or maybe just create a new web with New-SPWeb
}
else
{
   #do something else
}

Note that you can also add to error variable using +err and iterate error array.

Also note the AssignmentCollection. You should read up on that when you use object that need to be disposed, like SPSite and SPWeb:

 Get-Help Start-SPAssignment -full

Another option is using the Trap construct or try/catch/finally (PS V2 only)

More reading: -ErrorAction and -ErrorVariable

Trap in powershell

Tags:

Powershell