Accessing Web Parts From SharePoint Pages Using PnP PowerShell


Introduction

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


The Web parts from any SharePoint Server page (Publishing, Wiki or Site Pages) can be accessed 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 (Root)

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

  3. Connect-SPOnline -Url $siteurl  

  4. $ctx = Get-SPOContext  

There are multiple ways to retrieve the Web parts and the properties.


Retrieve Web Parts

The Web parts from the page can be easily accessed, using Get-SPOWebPart command with PnP PowerShell.

  • The required parameter for accessing all the Web parts is the Server relative URL of page.

  • The basic properties like title and Id of Web part and Web part zone detail can be accessed from $Webpart object (Object created for the command, given above).

  • All other properties can be accessed from the Web part properties object $Webpart.WebPart.Properties.FieldValues.

The following code snippet shows how to access the Web parts and their properties.

  1. $webparts = Get-SPOWebPart -ServerRelativePageUrl "/Pages/PnPPage.aspx"

  2. # if there are more than 1 webparts

  3. foreach($webpart in $webparts){       

  4. Write-Host "Zone " $webpart.ZoneId      

  5. Write-Host "WebPart Id " $webpart.Id       

  6. Write-Host "Title " $webpart.WebPart.Title      

  7.  # Other Web Part Properties can be accessed