Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 15 down vote accepted

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

$exists = (Get-SPWeb $url -ErrorAction SilentlyContinue) -ne $null
share|improve this answer
    
This seems to work, thanks very much. –  Dan May 16 '11 at 6:32
add comment

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()
share|improve this answer
    
+1, good answer :) –  Abe Miessler May 16 '11 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 May 16 '11 at 6:28
    
Do you prefix the url with protocol moniker such as http://? It is obligatory I believe. –  Alexey Krasheninnikov May 17 '11 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 –  Alexey Krasheninnikov May 17 '11 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. –  Alexey Krasheninnikov May 17 '11 at 10:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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