Friday, August 3, 2012

How to create sub site with custom site template through PowerShell

Below is a complete version of PowerShell script to create and delete sub site.

Please let me know if you found any problem or have any suggestion.


---------------Create a sub site-----------------------

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue"

$ParentSiteUrl = "http://server/sites/SiteA"
$SiteTemplateTitle = "MySiteTemplate"

$ParentWeb = Get-SPWeb $ParentSiteUrl
$SiteTemplates = $ParentWeb.GetAvailableWebTemplates($ParentWeb.Language)
$SiteTemplate = $SiteTemplates | Where-Object {$_.Title -eq $SiteTemplateTitle}

function CreateSubSite([string]$SiteUrlName, [string]$SiteName)
{
$SiteUrlName = $ParentSiteUrl + $SiteUrlName

$SubWeb = New-SPWeb $SiteUrlName -Name $SiteName -UseParentTopNav
$SubWeb.ApplyWebTemplate($SiteTemplate.Name)

Write-Host "Web:" $SubWeb.Title " created!"

$SubWeb.Dispose()
}

CreateSubSite "SubSite1" "Sub Site 1"

$ParentWeb.Dispose()

rm function:/CreateSubSite

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

---------------Delete a sub site-----------------------
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue"

$ParentSiteUrl = "http://server/sites/SiteA"

function DeleteSubSite([string]$SiteUrlName)
{
$SiteUrlName = $ParentSiteUrl + $SiteUrlName
Write-Host "SiteUrlName:" $SiteUrlName

Remove-SPWeb $SiteUrlName -Confirm:$false
Write-Host "Web:" $SubWeb.Title " deleted!"
}

DeleteSubSite "FacilityTestSiteA"

rm function:/DeleteSubSite

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

No comments:

Post a Comment