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("")
$pubweb = [Microsoft.SharePoint.Publishing.Publishing.]::GetPublishing.($web)
$webpart=new-object  Microsoft.SharePoint..PartPages.ContentEditor.Part
$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.


Protected with Antivirus