This script performs the cleanup tasks done by the WSUS cleanup wizard. Because it is a script, it can be automated (for example, via the Windows Task Scheduler). It also provides extended support for computer cleanup, allowing one to specify the number of days of not hearing from the computer before cleanup (default is 30 days), and to optionally skip deletion of computers that are still in Active Directory Directory Services (to avoid accidently removing computers that are still around but having trouble contacting the server). We recommend also performing SQL defragmentation sample script as part of WSUS cleanup.

This script will run on any machine on which both Windows PowerShell and WSUS are installed. This script must be run from an account that has administration rights to the WSUS server. This script can also be adapted to run from a remote machine which has Windows PowerShell and the WSUS remote console installed changing the GetUpdateServer() call to GetUpdateServer(servername, true|false), where servername is the name of the remote WSUS server, and true|false refers to the use of SSL to make the connection. This script takes awhile to run, so be patient.

 | out-null
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer();
$cleanupScope = new-object Microsoft.UpdateServices.Administration.CleanupScope;
$cleanupScope.DeclineSupersededUpdates = $true       
$cleanupScope.DeclineExpiredUpdates         = $true
$cleanupScope.CleanupObsoleteUpdates     = $true
$cleanupScope.CompressUpdates                  = $true
#$cleanupScope.CleanupObsoleteComputers = $true
$cleanupScope.CleanupUnneededContentFiles = $true
$cleanupManager = $wsus.GetCleanupManager();