I am an nube to Powershell, so I think I have a pretty basic question here....

How do I determine if a SPWeb exists? I want to perform some operations on a site based on a URL passed in as a parameter. However, there are instances where the site may not exist. I have tried something like

where $siteToGet is not a valid site. However, I get an error message on the Get-SPWeb saying in red saying the site does not exist. The rest of the code then runs. Is this okay? I would prefer to log a message instead of display the error message from Get-SPWeb. It also causes more error messages as my script continues to run, but by checking for $null I can at least make sure I am not executing further code.

Any ideas how to check for the existence of a site using PowerShell and SharePoint 2010?

Anders-I tried my code on a site that didn't exist and I got no errors. I got the expected "site does not exist". Wonder if something is different between our environments???
–
Rob WilsonAug 10 '10 at 13:48

Nevermind. I see what I did wrong. Thanks for clearing it up, Anders.
–
Rob WilsonAug 10 '10 at 16:13

When I tried your code I also got a red error, but it seemed to indicate that it couldn't find the Get-SPWeb command -- which in turn caused the test to equal null. I wonder if by chance you didn't have the SharePoint snap-in loaded. The first block of code below ensures that the snap-in is loaded.

The PowerShell ISE works great for testing this script interactively if you aren't using it already. When I execute the following script, all of the tests show that the site or sub-site exists:

REVISED CODE BELOW PER ANDERS' OBSERVATIONS:
I revised this for my own sake and for the sake of anyone who would like to see a complete solution. Thanks for the tips, Anders!

# check to ensure Microsoft.SharePoint.PowerShell is loaded if not using the SharePoint Management Shell
Add-PSSnapin "Microsoft.SharePoint.Powershell" -ErrorAction SilentlyContinue # -EA 0 works also
$siteURL="http://pcrob7/robsubsite" # works for sites and site collections
$site = Get-SPWeb $siteUrl -ErrorVariable err -ErrorAction SilentlyContinue -AssignmentCollection $assignmentCollection
if ($err)
{
# Write-Error/Write-Warning or maybe just create a new web with New-SPWeb
Write-Host Site Collection $siteToGet does not exist
}
else
{
Write-Host Site $siteToGet DOES exist
}