# WEC Script to keep the Registry Groomed.  Important for continued functionality over the life of the product.
# If the registry path contains more than 1000 items it can take a few minutes to open Eventviewer
# If the registry path contains more than 50,000 items, then the Eventviewer MMC won't open and the only option is using Wecutil.exe
# If the registry path contains more than 100,000 items, then the WEC server needs to be rebuilt.
# Run this script as a scheduled task to keep things running smoothly.
# Must run the script as admin

# Set how many days in the past to groom the registry
$date = ((Get-date).AddDays(-30)).ToFileTimeUtc()

# Path to the WEC Subscriptions
$keys = Get-ChildItem -Recurse HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\EventCollector\Subscriptions\

Foreach ($key in $keys) {
    $kname = $key | Get-ItemProperty | select PSChildName
    $klht = $key | Get-ItemProperty | select LastHeartbeatTime
    if ($klht.LastHeartbeatTime -gt $date) {  }
    else { 
            if ($key.PSPath -like "*EventSources\*") { 
                Write-Host about to delete $key.Name
                Remove-Item -Path $key.PSPath 
                }
            else { write-host $key.Name not contained EventSources\ }
            }
}
