Creating SharePoint 2010 site structure automatically with PowerShell
Just came back from a usergroup meeting where Charles Cote was talking about PowerShell and got inspired to share a piece of script that does site auto provisioning in SharePoint 2010.
Whether you have a complex site hierarchy or just want to automate simple deployment having an automated script that reads from configuration file and creates a site structure and activates relevant features is a real time saver.
Here is a simple XML file I created to define my site structure and any other relevant info (FYI: it`s really up to you how you want this structure to look like – I just created it from the top of my head)
<Setup WebAppUrl=”http://mywebappurl”>
<SiteCollection Name=”Site Collection Name” Url=”/sites/mysitecollection” OwnerAlias=”my_install_username” Template=”STS#0″>
<Site Name=”MySite” Url=”MySite” Template=”STS#0″>
<Feature>FeatureName</Feature>
</Site>
<Site Name=”MySite1″ Url=”MySite1″ Template=”STS#0″>
</Site>
</SiteCollection>
</Setup>
Now, in the script below, assuming you have a basic PowerShell 2.0 knowledge, I will read the XML and run through the loop of defined structure elements to create a new site based on parameters provided in the XML (SiteStructure.xml):
[xml]$SiteStructure = get-content SiteStructure.xml
$WebAppUrl = $SiteStructure.Setup.Attributes.Item(0).Value
$SiteCollectionUrl = $SiteStructure.Setup.SiteCollection.Attributes.Item(1).Value
$SiteUrl = $WebAppUrl + $SiteCollectionUrl
for ($i=0; $i -lt $SiteStructure.Setup.SiteCollection.ChildNodes.Count; $i++ )
{
$childsite = $SiteStructure.Setup.SiteCollection.ChildNodes.Item($i);
$WebName = $childsite.Attributes.Item(0).Value
$WebUrl = $childsite.Attributes.Item(1).Value
$WebTemplate = $childsite.Attributes.Item(2).Value
Write-Host “Creating new web at” $SiteUrl/$WebUrl
$NewWeb = New-SPWeb $SiteUrl/$WebUrl -Template $WebTemplate -Addtotopnav -Useparenttopnav -Name $WebName
Write-Host “Web created successfully”
Write-Host “Title:” $NewWeb.Title -foregroundcolor Green
Write-Host “URL:” $NewWeb.Url -foregroundcolor Green
$features = $SiteStructure.Setup.SiteCollection.ChildNodes.Item($i)
if($features.Feature.Length -gt 0)
{
foreach ($WebFeature in $features.Feature)
{
$ActivatedFeature = Enable-SPFeature $WebFeature -url $NewWeb.Url
Write-Host “Enabled Feature:” $WebFeature -foregroundcolor Green
}
}
Write-Host “…”
}
In here I showed how you can create webs, but hey, you can really create site collections too following the same pattern. Hope this will help you to streamline your deployments!





