Working with web parts programmatically across pages is awkward but possible in PowerShell. Let’s start by generating a report of the web parts. This iterates through non-admin web apps, site collections, and pages:
$oContentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService;
[Microsoft.SharePoint.Administration.SPWebApplicationCollection]$waCollection = $oContentService.WebApplications;
$log = ".\results.txt" # output file name and path
$pagepath = "/default.aspx" # you can change page name or page path
"Site URL; WebPart Title ; Webpart ID" | out-file $log
$waCollection1 = $waCollection | where-object {$_.IsAdministrationWebApplication -eq $FALSE}
foreach ($wa in $waCollection1)
{
foreach ($obj in $wa.Sites)
{
write-host "Processing site: " , $siteURL
$siteURL = $obj.URL
$site=new-object Microsoft.SharePoint.SPSite($siteURL)
$pageURL = $siteURL + $pagepath
$web=$site.Openweb()
$webpartmanager=$web.GetLimitedWebPartManager($pageURL, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
foreach ($webpart in $webpartmanager.WebParts)
{
$siteURL + "; " + $webpart.Title + " ; " + $webpart.ID | out-file $log -append
}
}
</pre>
As an example, we can remove web parts programmatically, by specifying the site collection and Web Part GUID:
$siteURL = "ht tp://SharePoint/sites/specialsite"; # first constant: site URL
$webpartId = "; # second argument: webpart GUID
$pagepath = "/default.aspx" # change page name or page path here
$pageURL = $siteURL + $pagepath
write-host "Processing site: ", $siteURL
Write-host "Processing page: " , $pageURL
write-host "Processing webpart ID: " , $webpartID
$site=new-object Microsoft.SharePoint.SPSite($siteURL)
$web=$site.Openweb()
$webpartmanager=$web.GetLimitedWebPartManager($pageURL, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$webpartmanager.DeleteWebPart($webpartmanager.Webparts[$webpartId])
$web.Update()
$web.Dispose()
write-host "Finished."
Want to talk?
Drop us a line. We are here to answer your questions 24*7.