Introduction
In this article, we will see how you can update the web part property of a custom web part on your SharePoint Online page using PnP PowerShell script. Sometimes, due to heavy customization on a SharePoint page, you may not be able to see and update the value of a web part property even in edit mode. In that case, you need to use a PowerShell script to update the web part properties.
PowerShell script
This PowerShell script modifies a web part on a SharePoint Online site page (custompage.aspx) using the PnP PowerShell module.
The below PowerShell code is using PnP PowerShell to establish an authenticated app-only connection to a SharePoint Online site using Azure AD credentials (client ID and secret).
#Store the Azure AD Application (client) ID used for app-only authentication
$_sClientID = "xxxxx-1111-0000-9999-yyyyyyy";
#Store the client secret (password) for the above app registration.
$_sClientSecret = "xyxyxyxyxyywCc90dfoztytzyz"
# Specify the SharePoint Online site URL to connect to.
$siteUrl = "https://xyz.sharepoint.com/sites/Intranet"
# Establish a connection to SharePoint Online. Store the connection object (in $_oConnection) for reuse in other commands.
$_oConnection = Connect-PnPOnline -Url $siteUrl `
-ClientId $_sClientID -ClientSecret $_sClientSecret `
-WarningAction Ignore -ReturnConnection -Verbose:$false
The PowerShell script is modifying a web part on a SharePoint Online site page (webPartPage.aspx) using the PnP PowerShell module.
#Below line defines the new link (URL) you want to set in the web part property. This html page is used by webpart to show some data.
$customPage = https://test.insight.com/ODG/pages/Custom.html
#This line fetches all web part components from the webPartPage.aspx page. $Page contains an object representing a web part
$Page = Get-PnPPageComponent -Connection $_oConnection -Page webPartPage.aspx
#Below line parses the current settings/configuration (in JSON format) of the web part into a PowerShell object for editing
$settings = $Page.PropertiesJson | ConvertFrom-Json
#Below line updates the contentLink property of the web part to the new URL (Custom.html)
$settings.contentLink = $customPage
#Below line applies the updated properties back to the specific web part (identified by its InstanceId) on the webPartPage.aspx page.
Set-PnPPageWebPart -Connection $_oConnection -Page webPartPage.aspx -PropertiesJson ($settings | ConvertTo-Json) -Identity $Page.InstanceId
Summary
In this article, we discussed a PowerShell script which is doing following activities:
- It logs in to a SharePoint Online site (/sites/Intranet) using an Azure AD App (not a user account) and saves that connection into $_oConnection.
- Connects to a SharePoint Online page (webPartPage.aspx),
- Finds a specific web part,
- Changes its contentLink property to point to a new URL (Custom.html),
- And saves the changes back to the page.