Delete a web part from all pages in a site collection

Scenario:
One of your custom web parts becomes obsolete and you decide to remove from all pages where is is used.

Powershell Script:

 Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue  
 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.WebPartPages")  
 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing")  
 $wpName = "Register CSS web part";  
 $siteUrl = "http://site:port"  
 $libraryNames = @("Pages");  
 $site = Get-SPSite $siteUrl;  
 $checkedOut = @()  
 foreach($spweb in $site.AllWebs)  
 {  
      $url = $spweb.Url;  
      Write-Host "Processing $url"  
      foreach($lib in $libraryNames)  
      {  
           $list=$spweb.Lists[$lib]  
           foreach($item in $list.Items)  
           {  
                $WebPageUrl = $item.Url  
                if ($WebPageUrl.length > 0)  
                {  
                     Write-Host "Processing page $WebPageUrl"  
                     $spWpManager = $spweb.GetLimitedWebPartManager($WebPageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared);  
                     $webparts = @()  
                     if ($item.File.CheckOutType -ne "None")  
                     {  
                          $checkedOut = $checkedOut + $WebPageUrl + ","  
                     }  
                     foreach($spwebpart in $spWpManager.Webparts)  
                     {  
                          if($spwebpart.Title -eq $wpName)  
                          {  
                               $webparts = $webparts + $spwebpart.ID    
                          }  
                     }  
                     foreach($webpartId in $webparts)   
                     {  
                          Write-Host "Deleting " + $spwebpart.Title + " from " + $item.Name  
                          $spWpManager.DeleteWebPart($spWpManager.Webparts[$webpartId])  
                     }  
                }  
           }  
      }  
      if ($checkedOut -ne @()) {  
           Write-Host "The following pages were checked out and could not be processed: $checkedOut" -foreground yellow   
           }  
      $spweb.Update();  
      $spweb.Dispose();  
      $checkedOut = @()  
      if($spWpManager -ne $null)  
      {    
           $spWpManager.Dispose();  
      }    
 }  

Leave a Reply