Adding Web Parts To SharePoint Pages Using Pnp Powershell


Introduction

In this article, we will learn how to add the Web parts to SharePoint pages on SharePoint sites, using PnP PowerShell. The Client Side Object Model is used internally for these operations.


The Web parts, present on the site, can be added to any SharePoint Server page (Publishing, Wiki or Site Pages) on the sites.


Prerequisite

You need to have PowerShell 3.0 available on a Windows machine. You need to install or import PnP PowerShell packages. You can download the installers or view more documentation from the official Website. The installers are available here. Online version installer is preferred for On Premise or Office 365 operations. You can also install all the three installers for testing (SharePoint 2013, 2016, online).


The PnP PowerShell is supported by SharePoint 2013, SharePoint 2016 On Premises and Office 365 versions. The following operations are tested on SharePoint 2013 and Office 365 environments.


Connect To Site

Connect to the site, using the snippet, given below. PnP PowerShell code, given below, helps in getting the current context of the site, using the Client Side Object Model (CSOM):

  1. #Get Current Context Site

  2. $siteurl = "https://abc.sharepoint.com"

  3. Connect-SPOnline -Url $siteurl  

  4. $ctx = Get-SPOContext  


Add Web Parts to Pages

There are two ways of adding a Web part to a page (site page or publishing page).


Referring Local File:

The Web parts, available on the SharePoint site, can be added to SharePoint pages, using PnP PowerShell. Add-SPOWebPartToWebPartPage command is used to add the Web parts. The required parameters are: 

  • Server relative URL of the page.

  • Path of the Web part XML file or XML data.

  • Zone Id.

  • Zone index. 

The corresponding Web part XML should be built before adding a Web part to the page. The XML structure differs for each Web part types (OOB/Custom/Content Editor/etc).


For example, following content shows the Web part XML for the content editor Web part.

  1. <?xml version="1.0" encoding="utf-8"?>

  2. <WebPart xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:x