office-365-advent-calendar

Scenario

You’ve got a Web Part which you want to add to one, but more likely multiple web part pages in a SharePoint Online Site. Or maybe even on multiple pages across multiple sites. You could do this manually, but adding the same web part with the same configuration over and over again may not be a productive use of it. Let’s make use of PowerShell to do this!

Code

The code itself is quite simple, as the PnP PowerShell cmdlets contain a cmdlet named Add-PnPWebPartToWebPartPage. All you need is the page where you want to add the web part as well as the XML of your web part.

Let’s say you’ve got a “This SharePoint site will be archived on 31/12/2016” message which you want to add to the default.aspx page on a list of sites. You can create the Web Part with the desired message and formatting once, then export it:

Once exported, you can use the following script to add the same web part to all default.aspx pages on all sites listed in SitesToArchive.csv. The Web Part will be added to the Zone named “Left” with an index of 0, that is at the top of it:

$cred = Get-Credential
$websToUpdate = Import-Csv SitesToArchive.csv
foreach($web in $websToUpdate) {
	write-host "Connecting to $($web.Url)"
	Connect-PnPOnline -Url $web.Url -Credentials $cred
	Add-PnPWebPartToWebPartPage -ServerRelativePageUrl "default.aspx"`
	-Path "c:\users\rmodery\Desktop\ArchiveMessageWebPart.dwp" -ZoneId "Left" -ZoneIndex 0
}

 

How about wiki pages in SharePoint Online? Add-PnPWebPartToWikiPage may help you here!

7 thoughts on “Office 365 Advent Calendar – 18 Adding a Web Part to a SharePoint Online Page with PowerShell”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.