Creating SharePoint sites from xml using Powershell

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:

                                                                                                                           

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.