Saturday, April 6, 2013

Powershell add a document library to a set of sub sites recursively

So during one of my many experiments the other day I found I needed a document library on all of my orders sites that had a custom web part page in it. While there are several ways of doing this with Powershell I chose to loop through my sub sites and add the DashboardSitePages document library to each site from scratch. I also wanted to add a web part page to this library named Dashboard.aspx.

Hey for some reason my script pasting function is not rendering the xml line very well below so here is a link to the complete script file.

## DESCRIPTION
## ------------------------------------------------
## Script to loop through a set of Subsites and  
## adds a document library named SitePages  and a 
## web part page to the site named dashboard.aspx
 
## EXPLAINATION
## ------------------------------------------------
## This example illustrates how to loop through a  
## set of sub sites and add a document library and a 
## web part page named dashboard.aspx 

##
## BEGIN
## ------------------------------------------------
## Load up the snapin so Powershell can work with SharePoint
## if the snapin was already loaded don't alert the user
Add-PSSnapin microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
## Clear any errors or output to the screen
CLS
## Set variables
## This variable will be the site where I want to start
$parentSite = "http://sp2010/dashboards"
$webSites = Get-SPWeb $parentSite

$layoutTemplate = 2
$documentLibraryDescription = "A Document Library to store the Dashboard Pages"
$pageTitle = "Dashboard"
$targetLibrary = "DashboardSitePages"

function CreateSitePagesDocLib
{
 $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
 $webSite.Lists.Add($targetLibrary, $documentLibraryDescription, $listTemplate)
 $docLib = $webSite.Lists[$targetLibrary]
 $docLib.OnQuickLaunch = $true
 $docLib.EnableVersioning = $true
 $docLib.Update()
 CreateDashboardPage
}

function CreateDashboardPage
{
 $list = $webSite.GetList("http://sp2010/dashboards/$webSiteName/SitePages/")
 $xml = "" + $list.ID + "NewWebPageNewWebPartPage" + $layoutTemplate + "true" + $pageTitle + ""
 
 $result = $webSite.ProcessBatchData($xml) 
}

foreach($webSite in $webSites.Webs)
{
 $webSiteName = $webSite.Name
 $webSiteDescription = $webSite.Description
 $sitePagesLib = $webSite.Lists[$targetLibrary]
 if($sitePagesLib)
 {
  CreateDashboardPage
 }
 else
 {
  CreateSitePagesDocLib
 }
}

No comments: