Wednesday, November 7, 2012

How to delete webparts from webpart gallery using powershell

Scenario: Deleting multiple WebParts from WebPart gallery using PowerShell

Solution:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-null

$Url = 'http://portal.sharepoint.com'

$site = Get-SPSite $Url

$wpCatlog =[Microsoft.SharePoint.SPListTemplateType]::WebPartCatalog

$list = $site.GetCatalog($wpCatlog)

$wpID = New-Object System.Collections.ObjectModel.Collection[System.Int32]

foreach ($item in $list.Items)
{
  if($item.DisplayName.ToLower().Equals("webpartname1"))
  {   $wpID.Add($item.ID) }
}

foreach($wp in $wpID)

   $wpItem = $list.GetItemById($wp)
   $wpItem.Delete()
}
$list.Update()