Create SharePoint 2010 sites using PowerShell reading an XML file

12 02 2010

Just a quick post to show how easy it is to create some sites in SharePoint 2010 using PowerShell by reading an XML file. I’m sure there are some powershell experts out there that can improve the code, but if you need to create a revision gateway during lunch this is the place to start.

Lets start by opening PowerShell with modules on the sharepoint server.

Create a sample xml file:

"<Setup>
 <Sites>
 <TopSiteName>Site1</TopSiteName>
 </Sites>
 <Sites>
 <TopSiteName>Site2</TopSiteName>
 <SubSiteName>Subsite2a</SubSiteName>
 <SubSiteName>Subsite2b</SubSiteName>
 </Sites>
 <Sites>
 <TopSiteName>Site3</TopSiteName>
 <SubSiteName>Subsite3a</SubSiteName>
 <SubSiteName>Subsite3b</SubSiteName>
 <SubSiteName>Subsite3c</SubSiteName>
 </Sites>
</Setup>" | out-file sample.xml

Now we have some data to work with we can create the sites. Three top sites will be created with 2 and 3 subsites below Site2 and Site3. They can be created using:

[xml]$s = get-content sample.xml
foreach ($e in $s.Setup.Sites){
$v = $e.TopSiteName
$b = $e.SubSiteName
new-SPWeb http://sp2010rc/$v -template "STS#0" -addtotopnav -useparenttopnav -name $v
if($b.Length -gt 0) {
foreach ($b in $b){
new-SPWeb http://sp2010rc/$v/$b -template "STS#0" -name $b -AddToQuickLaunch -useparenttopnav
}
}
}

The bit that creates the site is the new-SPWeb command. For information about the command switches run:

get-help new-SPWeb -full

It’s as easy as that! You will now have some SharePoint 2010 sites created in a matter of seconds.

To remove sites you can just use the remove-SPWeb command. This can be scripted in the same way:

[xml]$s = get-content sample.xml
foreach ($e in $s.Setup.Sites){
$v = $e.TopSiteName
$b = $e.SubTopSiteName
if($b.Length -gt 0) {
foreach ($b in $b){
remove-SPWeb http://sp2010rc/$v/$b
}
}
remove-SPWeb http://sp2010rc/$v 

}

The xml file can then be deleted with “Remove-Item sample.xml”

If you really wan’t to get stuck in run “Get-Command -module Microsoft.SharePoint.PowerShell” This will output all the cmdlets that you can use with PowerShell to do great things with SharePoint 2010 combine this with get-help and there is no limit to where you can go!!

So there we have it; One XML file with a site structure creating all the SharePoint 2010 sites in just a few seconds!

Happy site creating. Comments and experiences welcome.








Follow

Get every new post delivered to your Inbox.