Sunday, 11 November 2012

Adding Web part on pages using PowerShell script

One of the requirements in our project is to replace the existing webpart from our production site which was causing lots of problem with performance.  This web part was available on multiple content pages. So one of the option available to us is write PowerShell script to add new web part on multiple content pages.
So here I will discuss adding webpart on one SharePoint page using PowerShell script.
  1. To add the web part we will require web part definition file should be available on file system so that we can add it in webpart gallery, import and add it using WebPartManager class
  2. Now, consider we need to add the webpart on MyWPPage.aspx page from the page library of web MyWeb
  3. We need to get publishing web instance from web instance and allow unsafe updates to true as follows:
  4. Get the pages library and find the your list item as follows
  5. Get the file from listitem, check that if this page is checked out to other user or same user, in case same user then publish and then check out the page
  6. Now from local file system, get the file stream and import it using webpart manager as follows
  7. Finally, Check in the page and clean up the instances

$webURL = “”
$web = Get-SPWeb $webURL
#Get the publishing web instance and set allow unsafe update property to true
[Microsoft.SharePoint.Publishing.PublishingWeb]$pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web);
$allowunsafeupdates = $web.AllowUnsafeUpdates
$web.AllowUnsafeUpdates = $true
$list = $web.Lists[$pagesLibrary]
foreach($listItem in $list.Items){
if($listitem.URL.Contains("MyWPPage.aspx ") {
            $myListItem = $listItem

$page = $web.GetFile($listitem.URL)
if ($page.CheckOutStatus -ne "None")           {
#Check to ensure the page is checked out by same user, and if so, check it in
    if ($page.CheckedOutBy.UserLogin -eq $web.CurrentUser.UserLogin)
        $page.CheckIn("Page checked in automatically by PowerShell script")
        Write-Output $page.Title"("$page.Name") has been checked in"
if ($page.CheckOutStatus -eq "None"){
#Get the webpart manager
$webpartmanager = $web.GetLimitedWebPartManager($page.URL, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$saveFolder = "C:\webpart\"
$webpartfile = “MyWebPart.webpart”
$fileDWP = $saveFolder + $webpartfile
write-output "DWP File"  $fileDWP

#Getting the webpart gallery
[Microsoft.SharePoint.SPList]$wpList = $web.Site.GetCatalog([Microsoft.SharePoint.SPListTemplateType]::WebPartCatalog)
$fileStream = ([System.IO.FileInfo](Get-Item $fileDWP)).OpenRead()
[Microsoft.SharePoint.SPFile]$wpFile = $wpFolder.Files.Add($webpartfile, $fileStream, $true)
Write-host $wpFile
 [System.Xml.XmlReader]$xmlReader = [System.Xml.XmlReader]::Create($wpFile.OpenBinaryStream())
#Import the webpart
$myCustomWP = $webpartmanager.ImportWebPart($xmlReader,[ref]$errorMsg)
Write-Output "My custom WebPart" $myCustomWP.title
#If this webpart is not available on page then add it
if(! $webpartmanager.WebParts.Contains($myCustomWP)){
$webpartmanager.AddWebPart($myCustomWP, $wpZoneId, $wpOrder)

$page.CheckIn("Page checked in automatically by PowerShell script")
$page.Publish("Page published,new webpart added")
$web.AllowUnsafeUpdates = $allowunsafeupdates
Your feedback / comments are most welcome
Enjoy SharePoint :)


Rajganesh Mountbatton said...


Thank you for your script. When I am using the script, I am getting exception while executing the line

[Microsoft.SharePoint.SPFile]$wpFile = $wpFolder.Files.Add($webpartfile, $fileStream, $true)

I think the value for $wpFolder is not set. Can you pls help here?


Prasham Sabadra said...

Hello Rajganesh,

Thanks for finding this. You are correct. There one line is missed as follows:

[Microsoft.SharePoint.SPFolder]$wpFolder = $wpList.RootFolder

We need to take RootFolder of WebPart Gallery library.

Please check now. Thanks again.

If something more required please let me know.

Mahen said...

Thank you for your script. It's really Helpful for me.

Prasham Sabadra said...

Hi Mahen,

Nice to hear that script is helpful to you.

Cindy Dy said...

Excellent and decent post. I found this much informative, as to what I was exactly searching for. Thanks for such post and keep it up.


portalguyct said...

This was really what I needed. I had been struggling with similar code all day, and when I saw this, I was able to complete my project.

Please be aware - this works great on a Web Part page, but not a Wiki page. You have to manually add the web part on a Wiki page, or add a LOT more logic/code.

Prasham Sabadra said...


Glad to hear, it help you. For wiki page please check my another post


Karen Maxwell said... free SharePoint 2013 offers a great experience with added social media capabilities and website management that includes shared calendars, blogs, wikis, surveys, document libraries and more.