SharePoint Online: WebParts operation with PnP Powershell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

==================== Accessing Web Parts on Page ====================

Retrieving a single web part

 
Get-SPOWebPart -ServerRelativePageUrl "Relateive Path to your page" -Identity "Web Part Identity"

Retrieving web part properties

 
$wp = Get-SPOWebPart -ServerRelativePageUrl "Relateive Path to your page" -Identity "Web Part Identity"

#Common Properties
$wp.Id
$wp.Title
$wp.ZoneId

#Other Properties
$wpProps = $wp.WebPart.Properties.FieldValues  
foreach($prop in $wpProps){  
    $prop ["XmlDefinition"]
}

Retrieving all web parts on a page

#this returns you the collection of web parts
$wps = Get-SPOWebPart -ServerRelativePageUrl "Relateive Path to your page"
#to loop through all the webparts
foreach($wp in $wps){  
     #Same as above to retrieve properties
     $wp.Id
     $wp.Title
     #etc...
}

==================== Adding Web Parts ====================

Add to Wiki Pages

Add-SPOWebPartToWikiPage -ServerRelativePageUrl "Relative Path to your page" `
                         -Path "Path to your .webpart/.dwp file" -Row 1 -Column 1 

Add to Publishing Pages

*You must check out the page before you can add any web parts

Add web part using webpart/DWP file

#check out the page for edit
Set-SPOFileCheckedOut -Url "Absolute Path to your page"

#adding webpart
Add-SPOWebPartToWebPartPage -ServerRelativePageUrl "Relative Path to your page" `
                            -Path "Path to your webpart/dwp file" `
                            -ZoneId "Header" -ZoneIndex 0

#check in the page
Set-SPOFileCheckedIn -Url "Absolute Path to your page" -CheckinType MajorCheckIn

Add web part using XML data

This options usually is useful when you are dealing with variable replacement

#check out the page for edit
Set-SPOFileCheckedOut -Url "Absolute Path to your page"

#retrieve xml from file
[string]$xml = (Get-Content "Source Path to your webpart file") `
               -replace "~variable~", "target value"

#adding webpart
Add-SPOWebPartToWebPartPage -ServerRelativePageUrl "Relative Path to your page" `
                            -xml $xml -ZoneId "Header" -ZoneIndex 0

#check in the page
Set-SPOFileCheckedIn -Url "Absolute Path to your page" -CheckinType MajorCheckIn

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s