Thursday, March 28, 2013

Add Multiple WebParts using PowerShell Script

Hi All,


Imagine a scenario where you need to create 100 web part pages with different templates. You would spend a lot of time creating those pages. One of the approaches can be having a PowerShell script which can create web part pages for templates that you want.

Here is a simple script that creates web part pages in a loop.

[xml]$xmlfile = Get-Content ConfigFile.xml 

foreach( $sitecoll in $xmlfile.Configuration.SiteCollection) 
{ $site = $sitecoll.name }

 $spSite= Get-SPSite $site 
$web = $spSite.OpenWeb() 
$layoutTemplate = 4 # Template code 
$web = $spSite.OpenWeb() 
$list = $web.GetList("/sites/SharePointSite/SitePages/")
 $i = 1
 while ($i -le 5)
 { Write-Host $pageTitle = "WebPartPage& + $i 

$xml = "<?xml version=""1.0"" encoding=""UTF-8""?&gt;

<Method ID=""0,NewWebPage""><SetList Scope=""Request"">" + $list.ID + "</SetList><SetVar Name=""Cmd"">NewWebPage</SetVar><SetVar Name=""ID"">New</SetVar><SetVar Name=""Type"">WebPartPage</SetVar><SetVar Name=""WebPartPageTemplate"">" + $layoutTemplate + "</SetVar><SetVar Name=""Overwrite"">true</SetVar><SetVar Name=""Title"">" + $pageTitle + "</SetVar></Method>"

 $result = $web.ProcessBatchData($xml)

 $i++ 

Write-Host -foregroundcolor Green $pageTitle 'created successfully' 

}

and when you run here is the output of the script and then final result



If you observe closely here we have specified layouttemplate, we have specified 4. This related to various templates like three column, four columns, headers the template that we select while creating web part page.

 Possible LayoutTemplate values are :

# 1 - Full Page, Vertical
# 2 - Header, Footer, 3 Columns
# 3 - Header, Left Column, Body
# 4 - Header, Right Column, Body
# 5 - Header, Footer, 2 Columns, 4 Rows
# 6 - Header, Footer, 4 Columns, Top Row
# 7 - Left Column, Header, Footer, Top Row, 3 Columns
# 8 - Right Column, Header, Footer, Top Row, 3 Columns