How to run the WSUS Server Cleanup Wizard from command-line

When running the WSUS Server Cleanup Wizard from the MMC snap-in, it can occur that you receive the following WSUS database error:

Error: Database Error
An error occurred when trying to perform a database operation. This can happen if the database is very busy, if the database service is stopped, if the connection to the database is lost, of if the Post-Installation task is not completed successfully. Please contact your system administrator if the problem persists.

Click Reset Server Node to try to connect to the server again.

If you haven't performed the cleanup in a long time, then this can happen. So you might decide to read through the manual of the wsusutil.exe tool where you think that the deleteunneededrevisions switch will resolve all your problems, however, it seems that the wsusutil.exe parameter deleteunneededrevisions doesn't exist on WSUS 3.1.

Luckily, you can achieve the same thing using powershell. The advantages here are:

  • If you have used this powershell script once, you can use the Server Cleanup Wizard from the GUI again.
  • You can schedule the execution of this powershell script using Task Scheduler (for example once every month).
  • On my WSUS server, I had about 600GB of updates. After running this script, almost 2000 updates were compressed, saving almost 200GB of disk space!

If you save the contents of the powershell script to "WSUSCleanup.ps1", then you can execute this script as follows from a DOS Command Prompt window: powershell -file "WSUSCleanup.ps1"
Make sure that you open the DOS Command Prompt as administrator!

The script itself is only 11 lines long (13 if you include comments):

# WSUSCleanup.ps1

[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")` | 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();


# Script END

The output of the script looked as follows when I ran it the first time:

C:\scripts>powershell -file "WSUSCleanup.ps1"

SupersededUpdatesDeclined : 0

ExpiredUpdatesDeclined    : 0

ObsoleteUpdatesDeleted    : 3

UpdatesCompressed         : 1953

ObsoleteComputersDeleted  : 0

DiskSpaceFreed            : 168707192502


You might also be interested in...