Adding a web part to a page using CSOM / PowerShell

The following script adds a web part to a page using PowerShell and the Client Side Object Model (SharePoint 2013).

Prior to adding a web part to the page you need to:

  • Get the XML of the web part –  the easiest way is to export the web part and view the XML in Notepad. The XML will need to be stored as a variable in your script.

The basic steps:

  • Open a connection to the site collection
  • Get the page
  • Check out
  • Create the web part definition – using the XML from your exported web part
  • Add the web part to the page
  • Check in the page
# My previous code (not included) deals with connecting to my Site Collection hosted on Office 365 

# URL of page where we want to add the webpart
$serverRelativeUrl = '/sites/tDEV/pages/Contact-Us.aspx'
#  Get the page
$oFile = $ctx.get_web().getFileByServerRelativeUrl($serverRelativeUrl)
# Load and print out the Title of the page

# CheckOut the page
# Get the webpart manager
$limitedWebPartManager = $oFile.getLimitedWebPartManager("Shared")
# Import the web part using the web part XML, $wpxml contains the XML from the exported web part
$wpd = $limitedWebPartManager.ImportWebPart($wpxml)
# Using the web part definition we can add the webpart to the page - in the header zone.
$limitedWebPartManager.AddWebPart($wpd.WebPart, "Header", "1")
# Check in the page
$oFile.CheckIn("test", "MajorCheckIn")