Thursday, April 21, 2011

Powershell script to create nested subsites within a site collection

Our goal is to create 50 parent subsites and iteratively create 5 nested child subsites underneath each of them. So mathematically it is 50 subsites * 5 nested subsites per parent subsite = 250 nested sub-sites in total.

The powershell scriptlet below accepts Site Collection URL,  Site Collection Template, Site Collection Language, Sub-site Name and a Nested Sub-site name as configurable parameters, it then goes through each of them and creates nested sub-sites for that particular Site Collection.

Instructions:
1. Copy and Paste the code below and save it as CreateNestedSubSites.ps1, see highlighted yellow sections to change configurable values:

Add-PsSnapin Microsoft.SharePoint.PowerShell

## SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Creating Sub Sites in top site collection.
Write-Output " "
Write-Output "Creating 250 Nested Sub-Sites"

$SiteCollectionURL = "http://localhost/sites/NestedSubSites"

$SiteCollectionTemplate = "BLANKINTERNETCONTAINER#0"

$SiteCollectionLanguage = 1033

$StaplingWeb = "StaplingWeb"

$StaplingNestedSubWeb = "NestedWeb"

## Iterate via 50 Subsites
for($i=0 ; $i -lt 50 ; $i++)
{
    $SiteUrl = ""
    $SubSiteName = ""
    $SiteUrl = $SiteCollectionURL + "/"
    $SubSiteName = $StaplingWeb + $i
    $SiteUrl = $SiteUrl += $SubSiteName

    Write-Host "Creating Sub-Site for " $SubSiteName
    New-SPWeb $SiteUrl -Template $SiteCollectionTemplate -Name $SubSiteName  -UseParentTopNav -Language $SiteCollectionLanguage
    Write-Host "Site Created for " $SubSiteName
   
    ## Create 5 Subsites underneath each of the 50 subsites
    for($j=0 ; $j -lt 5 ; $j++)
    {
        $NestedSubSiteUrl = ""
        $NestedSubSiteName = ""
        $NestedSubSiteName = $StaplingNestedSubWeb + $j
       
        $NestedSubSiteUrl = $SiteUrl + "/"
        $NestedSubSiteUrl = $NestedSubSiteUrl += $NestedSubSiteName
       
        Write-Host "Creating Nested Sub-Site for :" $NestedSubSiteName
        New-SPWeb $NestedSubSiteUrl -Template $SiteCollectionTemplate -Name $NestedSubSiteName  -UseParentTopNav -Language $SiteCollectionLanguage
        Write-Host "Nested Sub-Site created for :" $NestedSubSiteName
    }
}

Remove-PsSnapin Microsoft.SharePoint.PowerShell

2. To automatically run the CreateNestedSubSites.ps1 script as a batch utility, Copy and paste code below and save it with a .bat file extension

cd /d %~dp0
powershell -noexit -file ".\CreateNestedSubSites.ps1" "%CD%"
pause


Run the Script and enjoy :)

No comments:

Post a Comment