Warm tip: This article is reproduced from serverfault.com, please click

Get list of SharePoint WebParts using Get-PNPWebPart

发布于 2020-12-11 00:33:43

In SharePoint Online I have create an out of the box site and added a couple of WebParts. I want to get the list of the WebParts and add them to other sites.

I'm using the command Get-PNPWebPart to get the WebParts from the site.

This is the code I have tried.

$user = "[username]"
$password = ConvertTo-SecureString "[password]" -AsPlainText -Force

$credentials = New-Object –TypeName "System.Management.Automation.PSCredential" –ArgumentList $user, $password
 
$siteURL = "https://[tenant].sharepoint.com/Sites/[site name]"
 
Connect-PnPOnline -Url $siteURL -Credentials $credentials

$serverRelativePageUrl = "/sites/[site name]/SitePages/Home.aspx"

$webparts = Get-PNPWebPart -ServerRelativePageUrl $serverRelativePageUrl

foreach($webpart in $webparts)
{
    Write-Host "WebPart title:" $webpart.WebPart.Title
}

When I run this I don't get any errors but the $webparts variable is empty.

Why is the $webParts variable empty when I try to get the list of WebParts from the SharePoint site?

Questioner
Høgsdal
Viewed
0
Jerry_MSFT 2020-12-11 10:55:04

Get-PnPWebPart is not valid for getting web parts in Modern Page(classic page will work).

Instead, please use the code snippet below to get web parts in Modern Site Home.aspx:

$user = "user@tenant.onmicrosoft.com"
$password = ConvertTo-SecureString "password" -AsPlainText -Force

$credentials = New-Object –TypeName "System.Management.Automation.PSCredential" –ArgumentList $user, $password
 
$siteURL = "https://tenant.sharepoint.com/sites/JerryModernTeam"

Connect-PnPOnline -Url $siteURL -Credentials $credentials


$page=Get-PnPClientSidePage -Identity "Home.aspx"



$webParts = $page.Controls  
#if there are more than one webparts  
foreach($webpart in $webParts) {  
    Write - Host "WebPart Id "  
    $webpart.InstanceId  
    Write - Host "Title "  
    $webpart.Title  
}  

Reference:

Add, Remove, And Get All Web Parts From Modern Site Page Using PnP PowerShell