Thursday, August 18, 2011

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

 $var=$webpartsarray.length
 #write-host $var

 for($j=0; $j -lt $var; $j++)
 {
 $webpartmanager.DeleteWebPart($webpartmanager.WebParts[$webpartsarray[$j]])

  # call CloseWebPart method to close the web part
 }

$SPweb.Update();
$SPweb.Dispose(); 

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



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

No comments :

Post a Comment

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...