Remove a Web Part Programmatically using PowerShell

We have had bunch of SharePoint 2007 site collections and recently upgraded them to SharePoint 2010. After the upgrade for some reasons, we wanted to delete a particular web part (Tip of the day web part) from the home page of All migrated sites' default.aspx page of the many sites.

I get into Maintenance mode (by just appending "?contents=1" to the end of URL) and deleted the particular web part.

But there are 1000+ sites migrated from SharePoint 2003, OMG! So, wrote the code to delete the error web parts Programmatically remove web parts. This saved my day!

Here is the code to remove web part on default.aspx page of a particular site:

Remove a Webpart Programmatically using PowerShell
$SPsite = Get-SPSite http://sharepoint-site/sites/admin/
$SPweb =  $SPsite.OpenWeb()  

$webpartmanager = $SPweb.GetLimitedWebPartManager(($SPweb.Url + "default.aspx"),  [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

   $webpartsarray = @()

 For($i=0;$i -lt $webpartmanager.WebParts.Count;$i++)
    if($webpartmanager.WebParts[$i].title -eq "Tip of the Day")  #Check for particular web part
      $webpartsarray = $webpartsarray + $webpartmanager.WebParts[$i].ID

 #write-host $var

 for($j=0; $j -lt $var; $j++)

  # call CloseWebPart method to close the web part


In an another case, I had a similar situation where a particular web part throws the error message. Actually those Error webpars are Site Tree web parts, which is not supported after SharePoint 2003. So Decided to delete the error webparts from the site rather fixing it.

"Error: Web Part Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. The type could not be found or it is not registered as safe."

So, I used the above technique with:

 if(!$webpartmanager.WebParts[$i].title)  #Check for Null


  1. Hi, this works for SharePoint 2013 as well, however, I would like to find a way to check all document libraries and lists and remove the web part from all of them.


Please Login and comment to get your questions answered!

Powered by Blogger.