How to add webPart to Page with PowerShell from WebPart Gallery

https://sharepoint.stackexchange.com/questions/233319/how-to-add-webpart-to-page-with-powershell-from-webpart-gallery



#ensure that you use the site collection root url 
#if you use subsite url, will throw error since webpart gallery 
#exists only in the site collection root site

$web = Get-SPWeb "https://site-collection-url"

$pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)

$publishingPage = $pubWeb.GetPublishingPage("https://site-collection-url/Pages/Test.aspx");

$publishingPage.CheckOut();

$list = $web.Lists["Web Part Gallery"]   

#use the webpart title or the .webpart file name

$wpl = $list.Items | where {$_.Title -eq "Your Webpart Name"}   

$xmlReader = New-Object System.Xml.XmlTextReader($wpl.File.OpenBinaryStream());   

$errorMsg = ""   

$wpManager = $publishingPage.ListItem.File.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared);

$webPart = $wpManager.ImportWebPart($xmlReader, [ref]$errorMsg)   

#insert webpart into header zone at index 1

$wpManager.AddWebPart($webpart,"Header",1)  

$publishingPage.CheckIn("Added webpart");

$publishingPage.ListItem.File.Publish("Published");

$wpManager.Dispose()

$web.Dispose() 

Comments

Popular posts from this blog

How to Create an Auto-Incrementing Number Field in a SharePoint List

SharePoint Integration with IIS

Error:Installing product D:\exchangeserver.msi failed. Fatal error during installation. Error code is 1603.