How to get webPart XML with powershell from SharePoint WebPart Gallery
-
07-01-2021 - |
Question
I want to get web part XML from SharePoint Web Parts Gallery(not locally) for add webpart into a List page.
This is my code:
$spWeb = Get-SPWeb $webURL
$spSiteCollection = Get-SPWeb -Identity $spWeb.Site.Url
$pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spSiteCollection)
$pageName = "$pageName.aspx"
$list = $spWeb.Lists[$listName]
$publishingPage = $list.RootFolder.Files | where {$_.Name -eq $pageName}
$publishingPage.CheckOut();
$webPartslist = $spSiteCollection.Lists["Web Part Gallery"]
#use the webpart title or the .webpart file name
$wpl = $webPartslist.Items | where {$_.Title -eq $webPartName}
$webPartFile = spWeb.GetFile($wpl.Url)
$xmlReader = New-Object System.Xml.XmlTextReader($webPartFile.OpenBinaryStream());
$errorMsg = ""
$wpManager = $publishingPage.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
Result is:
Solution
To add Web Part from SharePoint WebPart Gallery to publishing page, the following PowerShell for your reference.
$webURL="http://sp2013/sites/team"
$listName="Pages"
$pageName="Home"
$webPartName="SharePointProject1 - VisualWebPart1"
$spWeb = Get-SPWeb $webURL
$spSiteCollection = Get-SPWeb -Identity $spWeb.Site.Url
$pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spSiteCollection)
$pageName = "$pageName.aspx"
$list = $spWeb.Lists[$listName]
$publishingPage = $list.RootFolder.Files | where {$_.Name -eq $pageName}
$spWeb.AllowUnsafeUpdates = $true
if($publishingPage.ListItem.File.CheckedOutByUser -eq $null)
{
# Though it is newly created or already there, checkout.
$publishingPage.CheckOut()
}
$webPartGallery = $spSiteCollection.Lists["Web Part Gallery"]
#use the webpart title or the .webpart file name
$webpart=$webPartGallery.Items | ? { $_.Title -eq $webPartName}
if($webpart -eq $null) {
Write-Host("Unable to retrieve webpart: $fileName") -ForegroundColor Red
}
else {
Write-Host("----------Adding Webpart--------")-ForegroundColor Yellow
$webpartmanager=$publishingPage.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$errorMsg = "";
$xmlReader = New-Object System.Xml.XmlTextReader($webpart.File.OpenBinaryStream());
$webpart = $webpartmanager.ImportWebPart($xmlReader,[ref]"Error")
$webpartmanager.AddWebPart($webpart, "zone1", 1);
Write-Host("Webpart is added successfully") -ForegroundColor Green ;
}
# Check in the Page with Comments
$publishingPage.CheckIn("Added webpart")
# Publish the Page With Comments
$publishingPage.Publish("Publish")
$spWeb.AllowUnsafeUpdates = $false
More information: http://sharepointpals.com/post/How-to-Add-AppParts-to-Publishing-Pages-in-SharePoint-2013-using-PowerShell
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange