Thursday, February 25, 2010

How can we create a new SharePoint 2010 Site using Power Shell scripts?

Step 1: We need to create a Power Shell script file, say, createsite.ps1

# define variables for script
$SiteTitle = "My First Site using Power Shell"
$SiteUrl = ""
$SiteTemplate = "STS#1"

# check to ensure Microsoft.SharePoint.PowerShell is loaded
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}

if ($snapin -eq $null)
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"

# delete any existing site found at target URL
$targetUrl = Get-SPSite | Where-Object {$_.Url -eq $SiteUrl}

if ($targetUrl -ne $null)
Write-Host "Deleting existing site at " $SiteUrl
Remove-SPSite -Identity $SiteUrl -Confirm:$false

# create new site at target URL
Write-Host "Creating new site at " $SiteUrl
$NewSite = New-SPSite -URL $SiteUrl -OwnerAlias Administrator -Template $SiteTemplate -Name $SiteTitle
$RootWeb = $NewSite.RootWeb

# display site info
Write-Host "A new SharePoint Site has been created successfully" -foregroundcolor Green
Write-Host "-------------------------------------" -foregroundcolor Green
Write-Host "Site URL:" $RootWeb.Url -foregroundcolor Yellow
Write-Host "Site ID:" $RootWeb.Id.ToString() -foregroundcolor Yellow
Write-Host "Site Title:" $RootWeb.Title -foregroundcolor Yellow
Write-Host "-------------------------------------" -foregroundcolor Green

Step 2: To execute this script, you can create a bat file, say, setup.bat and execute the batch file

powershell -Command "& {Set-ExecutionPolicy bypass}" -NoExit
powershell -Command "& {.\createsite.ps1}" -NoExit