Working with Web Parts in PowerShell

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

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 = "<guid of your choice for webpart>;   # 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)
$webpartmanager=$web.GetLimitedWebPartManager($pageURL, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
write-host "Finished."
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *