Thursday, November 22, 2012

Create SharePoint 2010 sites using PowerShell reading an XML file

 

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.SubSiteName
if($b.Length -gt 0) {
foreach ($b in $b){
remove-SPWeb http://sp2010rc/$v/$b
}
}
remove-SPWeb http://sp2010rc/$v

}

No comments:

Post a Comment