Creating Site Structure using PowerShell and XML

This post is related to another recent post on creating pages using PowerShell and XML, but this time the focus is on creating sites (SPWebs, specifically :)) using PowerShell and XML input. I knew based on my prior experiences with creating Pages that XML was a nice, easy way to automate the tasks. Using the following XML syntax allowed me to put together what would work for my scenario:

<?xml version="1.0" encoding="utf-8"?>
    <SiteTitle>My First Site</SiteTitle>
    <SiteTitle>My Second Site</SiteTitle>

Really pretty simple – right? Now I did have other settings for my Webs, but they were static across all of my sites (Template, for example) so I haven’t included them here. However, you could easily add additional tags and logic to apply different templates, locale IDs, etc…

Once I had the XML, creating the sites was VERY easy. It’s literally just 24 lines of PowerShell code, with the work coming from the ForEach-Object cmdlet. (Note: I excluded my typical comment-based help for ease of reading.)

Without further ado, here is the PoSh code!

function New-SPWebFromXml {
# Read in list of sites from XML
[xml]$SitesXml = Get-Content $($XmlInput)
if ($SitesXml -eq $null) {return}
Start-SPAssignment -Global
$StartTime = Get-Date
# Loop through each site node to extract data
$SitesXml.Sites.Site | ForEach-Object {
$SiteTitle = [string]$_.SiteTitle
$SiteUrl = [string]$_.SiteUrl
$WebTemplate = "CMSPUBLISHING#0"
$LangId = "1033"
Write-Host "Creating an SPWeb at $($SiteUrl)"
New-SPWeb -Url $SiteUrl `
-Language $LangId `
-Template $WebTemplate `
-Name $SiteTitle
$EndTime = Get-Date
$TimeSpan = New-TimeSpan $StartTime $EndTime
Write-Host "$($SitesXml.Sites.Site.Count) sites created in $timespan"
Stop-SPAssignment -Global

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s