I have a script that exports a site and restores it in another web application. I want to check if the target site already exists. Is there an easy way to tell if www.example.org/sites/asite/ is free, without throwing an error in Powershell?
2 Answers
Using Powershell's ErrorAction you can suppress the error if a web does not exist.
$exists = (Get-SPWeb $url -ErrorAction SilentlyContinue) -ne $null
SharePoint 2010:
Get-SPWeb -Identity $url | Select-Object -Property Exists -ErrorAction SilentlyContinue
SharePoint 2007:
[void][reflection.assembly]::loadwithpartialname("Microsoft.SharePoint")
$siteCollection = New-Object Microsoft.SharePoint.SPSite($url)
$site = $siteCollection.OpenWeb()
Write-Host $site.Exists
...
$site.Dispose()
$siteCollection.Dispose()
-
-
This throws an error still: Get-SPWeb -Identity 'example.org' | Select-Object -Property Exists The 2007 version doesn't throw errors but returns true for sites that don't exist.– DanCommented May 16, 2011 at 6:28
-
Do you prefix the url with protocol moniker such as http://? It is obligatory I believe. Commented May 17, 2011 at 9:58
-
Get-SPWeb : Cannot find an SPSite object that contains the following Id or Url: example.org. -- this is what you get in case that web never existed Commented May 17, 2011 at 10:00
-
You can either swallow the error by using -ErrorAction SilentlyContinue or handle it using trap, try/catch or 2>&1. Read on PowerShell error handling elsewhere. Commented May 17, 2011 at 10:04