Delete closed web parts

Let me start off by saying I take no credit for writing this code. It was posted by CorbettMerrill in this technet post. That being said I made only 2 modifications so this script will now iterate down through all sites and sub-webs to look at the default.aspx and SitePages\Home.aspx and delete any web parts that are marked as closed. I am sure this can be customized further to encompass all sites but I have not had the time to sit and figure it out yet. A text file is attached with the code below:

[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | out-null
[void][System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$pageURL="default.aspx"

function SubWebs([Microsoft.SharePoint.SPWeb] $web)
{
$subwebs = $web.GetSubwebsForCurrentUser()

foreach($subweb in $subwebs)
{
SubWebs($subweb)
$subweb.Dispose()
}
$web | select Url
$file = $web.GetFile($pageURL)
$webpartmanager=$file.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$count = $webpartmanager.WebParts.Count
if ($count -eq 0) {
$file = $web.GetFile("SitePages\Home.aspx")
$webpartmanager=$file.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$count = $webpartmanager.WebParts.Count
}
for ($i=$count;$i -ge 0;$i--)
{
$webpart = $webpartmanager.WebParts[$i]
#If the webpart is closed, remove it
if ($webpart.IsClosed -eq $TRUE)
{
if ($file.RequiresCheckout -eq $TRUE) { $webpartmanager.Web.GetFile($file.UniqueID).CheckOut()}
$webpartmanager.DeleteWebPart($webpart)
if ($file.RequiresCheckout -eq $TRUE) { $webpartmanager.Web.GetFile($file.UniqueID).CheckIn("Deleted web part: " + $webpart.Title)}
write-host $webpart.Title "deleted from" $web.URL
}
}
}

function Pause ($Message="Press any key to continue...")
{
Write-Host -NoNewLine $Message
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host ""
}

write-host "This script will delete all web parts on this server that are"
write-host "currently in a closed (not displayed) status."
pause

$oContentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService;
[Microsoft.SharePoint.Administration.SPWebApplicationCollection]$waColl = $oContentService.WebApplications;

$waColl1 = $waColl | where-object {$_.IsAdministrationWebApplication -eq $FALSE}

foreach ($wa in $waColl1)
{
$waName = $wa.Name
$sites = $wa.Sites

  foreach ($obj in $sites)
{
$spSite = new-object Microsoft.SharePoint.SPSite($obj.Url)
$web=$spSite.Openweb()

    If ($web -ne $null)
{
SubWebs $web
$web.Dispose()
}
}
}

 

closed_webparts.txt