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 PowerShell script to remove web part on default.aspx page of a particular site:

Remove a Web part Programmatically using PowerShell

$SPsite = Get-SPSite https://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 another case, I had a similar situation where a particular web part throws the error message. Actually, those Error web parts are Site Tree web parts, which are not supported after SharePoint 2003. So decided to delete the error web parts from the site rather than 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

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

2 thoughts on “Remove a Web Part Programmatically using PowerShell

Leave a Reply

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