Creating SharePoint sites from xml using Powershell
Posted
by Norgean
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Norgean
Published on Thu, 12 Apr 2012 12:53:44 GMT
Indexed on
2012/04/12
23:31 UTC
Read the original article
Hit count: 345
It is frequently useful to create / delete web applications in a development environment.
If you need to create a structure, this can quickly become tedious.
Enter Powershell, xml and recursive functions.
Create the structure in xml. Something like:
<Sites>
<Site Name="Test 1" Url="Test1" />
<Site Name="Test 2" Url="Test2" >
<Site Name="Test 2 1" Url="Test21" >
<Site Name="Test 2 1 1" Url="Test211" />
<Site Name="Test 2 1 2" Url="Test212" />
</Site>
</Site>
<Site Name="Test 3" Url="Test3" >
<Site Name="Test 3 1" Url="Test31" />
<Site Name="Test 3 2" Url="Test32" />
<Site Name="Test 3 3" Url="Test33" >
<Site Name="Test 3 3 1" Url="Test331" />
<Site Name="Test 3 3 2" Url="Test332" />
</Site>
<Site Name="Test 3 4" Url="Test34" />
</Site>
</Sites>
Read this structure in Powershell, and recursively create the sites. Oh, and have cool progress dialogs, too.
$snap = Get-PSSnapin | Where-Object { $_.Name -eq "Microsoft.SharePoint.Powershell" }
if ($snap -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
function CreateSites($baseUrl, $sites, [int]$progressid)
{
$sitecount = $sites.ChildNodes.Count
$counter = 0
foreach ($site in $sites.Site)
{
Write-Progress -ID $progressid -Activity "Creating sites" -status "Creating $($site.Name)" -percentComplete ($counter / $sitecount*100)
$counter = $counter + 1
Write-Host "Creating $($site.Name) $($baseUrl)/$($site.Url)"
New-SPWeb -Url "$($baseUrl)/$($site.Url)" -AddToQuickLaunch:$false -AddToTopNav:$false -Confirm:$false -Name "$($site.Name)" -Template "STS#0" -UseParentTopNav:$true
if ($site.ChildNodes.Count -gt 0)
{
CreateSites "$($baseUrl)/$($site.Url)" $site ($progressid +1)
}
Write-Progress -ID $progressid -Activity "Creating sites" -status "Creating $($site.Name)" -Completed
}
}
# read an xml file
$xml = [xml](Get-Content "C:\Projects\Powershell\sites.xml")
$xml.PreserveWhitespace = $false
CreateSites "http://$($env:computername)" $xml.Sites 1
Easy!
Sensible real life implementations will also include templateid in the xml, will check for existence of a site before creating it, etc.
© Geeks with Blogs or respective owner