21

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?

0

2 Answers 2

30

Using Powershell's ErrorAction you can suppress the error if a web does not exist.

$exists = (Get-SPWeb $url -ErrorAction SilentlyContinue) -ne $null
0
8

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()
5
  • +1, good answer :) Commented May 16, 2011 at 4:43
  • 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.
    – Dan
    Commented 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.