Tuesday, November 11, 2014

PowerShell script for enumerating all web parts in Sharepoint web application

Sometimes for maintenance we need to enumerate all web parts in Sharepoint web application. The following script can be used for that:

   1: param( 
   2:     [string]$webAppUrl
   3: )
   4:  
   5: function Enum-Web-Parts-On-Page($item)
   6: {
   7:     $file = $item.File
   8:     Write-Host "    Enum web parts on page" $file.Url -foregroundcolor green
   9:  
  10:     $webPartManager = $file.Web.GetLimitedWebPartManager($file.Url,
  11: [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
  12:     $contains = $false
  13:     foreach ($wp in $webPartManager.WebParts)
  14:     {
  15:         Write-Host "      Web part:" $wp.GetType().FullName  -foregroundcolor green
  16:     }
  17: }
  18:  
  19: function Enum-Web-Parts-In-Web($w)
  20: {
  21:     Write-Host "  Check pages on web" $w.Url -foregroundcolor green
  22:  
  23:     $pw = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($w)
  24:     $pagesList = $pw.PagesList
  25:     $pagesList.Items | ForEach-Object { Enum-Web-Parts-On-Page $_ }
  26: }
  27:  
  28: function Enum-Web-Parts-In-SiteCol($site)
  29: {
  30:     Write-Host "Check sub sites in site col" $site.Url -foregroundcolor green
  31:     $site.AllWebs | ForEach-Object { Enum-Web-Parts-In-Web $_ }
  32: }
  33:  
  34: if (-not $webAppUrl)
  35: {
  36:     Write-Host "Specify web app url in webAppUrl parameter" -foregroundcolor red
  37:     return
  38: }
  39:  
  40: $wa = Get-SPWebApplication $webAppUrl
  41: $wa.Sites | ForEach-Object { Enum-Web-Parts-In-SiteCol $_ }

It enumerates all site collections in web application (line 41), then all sub sites in each site collection (line 31), all pages in each sub site (line 25) and finally all web parts on each page (lines 10-16). This script can be used e.g. if you need to find web part of particular type or title on all sub sites in your web application and make changes in them. Hope that this script will be useful in your work.

No comments:

Post a Comment