使用 Get-PNPWebPart 获取 SharePoint WebPart 列表

Get list of SharePoint WebParts using Get-PNPWebPart

在 SharePoint Online 中,我创建了一个开箱即用的网站并添加了几个 WebPart。我想获取 WebPart 的列表并将它们添加到其他站点。

我正在使用命令 Get-PNPWebPart 从站点获取 WebPart。

这是我试过的代码。

$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
}

当我 运行 时,我没有收到任何错误,但 $webparts 变量为空。

为什么当我尝试从 SharePoint 站点获取 WebPart 列表时 $webParts 变量为空?

Get-PnPWebPart 无法在现代页面中获取 Web 部件(经典页面可以)。

相反,请使用下面的代码片段在现代站点中获取 Web 部件 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  
}  

参考:

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