Print Shortlink

Using PowerShell to add and configure SharePoint 2010 webparts

When it comes to post deployment SharePoint solution maintenance – your users might ask you to add certain functionality to already deployed site. One way to achieve this would be manually adding web parts to each page. Another way, would be deploying a feature to perform adding the web part programmatically. Probably the easiest way is to leverage PowerShell to access object model and add the web part to each page of the site.

Let’s take a look at what’s involved in adding a simple content editor web part to the page:

1. Open SharePoint 2010 Management Shell

2. Execute the following script:

$site = new-object Microsoft.sharePoint.SPSite("")
$web=$site.Open.()
$pubweb = [Microsoft.SharePoint.Publishing.Publishing.]::GetPublishing.($web)
$defaultpage=$pubweb.GetPublishingPages()[$pubweb.DefaultPage]
$defaultpage.CheckOut()
$webpartmanager=$web.GetLimited.PartManager($defaultpage.Url, 
[System..UI..Controls..Parts.PersonalizationScope]::Shared)
$webpart=new-object  Microsoft.SharePoint..PartPages.ContentEditor.Part
$webpart.ChromeType=[System..UI..Controls..Parts.PartChromeType]::TitleOnly;
$webpart.Title="Yaroslavs Content Editor .part"
$webpartmanager.Add.Part($webpart, "Left", 0);
$defaultpage.CheckIn("Checked in .part")
$defaultpage.File.Publish("Published .part")
if ($defaultpage.ParentList.EnableModeration)
{
   $modInformation = $defaultpage.ModerationInformation
   if($modInformation.Status -ne [Microsoft.SharePoint.SPModerationStatusType]::Approved)
   {
      $defaultpage.ListItem.File.Approve("Approved Page")
   }
}

There you go; Now the web part will be added to the page with the specified properties.

If you have more than one site or web with more than one page – you can apply the code and iterate through the rest of the pages as required.

Enjoy!