Friday, January 22, 2010

Deleting WebPart from a WebPart Gallery using PowerShell

Here I shall show you how to delete a webpart of a list of webparts from the WebPart Gallery of a particular Sharepoint Site. webparts.txt contains the list of webparts that needs to be deleted from the gallery. Note that the webpart name should be in the form of webpart1.webpart or webpart.dwp as in the url http://myserver/_catalogs/wp/Forms/AllItems.aspx 

-------------

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.WebPartPages")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing")


$url = "http://myserver/"


$wps = Get-Content "c:\Powershell\webparts.txt"
$SPSite = New-Object Microsoft.SharePoint.SPSite($url)


foreach($wp in $wps)
{
$SPWeb = $SPSite.OpenWeb()
$WebPartGallery = $SPWeb.Lists["Web Part Gallery"]


$gall = $WebPartGallery.Items | select Name


$count = $gall.Count
$count
for ( $i =0; $i -lt $count;$i++)
  {
if ($gall[$i] -match $wp)
{
Write-Host "found"
$WebPartGallery.Items.Delete($i)
$SPWeb.Update()
Write-Host "$wp deleted"
}
  $SPWeb.Dispose()
  }
}
-------

Hope this helps someone....

2 comments:

  1. The script worked perfectly! Thanks a lot!

    ReplyDelete
  2. Great script, thanks!

    ReplyDelete