Thursday, June 6, 2013

Deleting a WebPart from the WebParts Gallery using PowerShell

So you have a requirement to remove a webpart or multiple webparts from the webparts gallery in SharePoint and you need to do this with Windows PowerShell. One thing to remember is that the webparts gallery is the same as any other gallery in SharePoint and your task can easily be achieved using PowerShell. The below code will remove a webpart from the webparts gallery:

function RemoveWebPartsFromGallery([string]$siteUrl)
{
# an array of the custom webparts that were built;
$customWebPart = New-Object System.Collections.ObjectModel.Collection[System.String]
$customWebPart.Add("CustomWebPart")

$site = Get-SPSite $siteUrl

# the default SP type for a webpart gallery;
$wpCatalog = [Microsoft.SharePoint.SPListTemplateType]::WebPartCatalog

$list = $site.GetCatalog($wpCatalog)

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

foreach ($item in $list.items)
{
foreach ($wps in $customWebPart)
{
if ($item.Name.ToLower().Equals($wps))
{
$wpID.Add($item.ID)
continue
}
}
}

foreach ($i in $wpID)
{
$wpitem = $list.GetItemById($i)
$wpItem.Delete()
}

$list.Update()

Write-Host "WEBPARTS REMOVED FROM GALLERY" -ForegroundColor Green
}

You can check out the original script here a big thanks to Srinivas Challagolla for the script. 

The script has greatly helped me I hope that it has helped you. Happy scripting guys :-)