After having migrated a WSUS role to a new Windows 2012R2 Server I was looking for a way to run the WSUS Server cleanup automatically on a schedule. Once a month seems to be sufficient as Microsoft has move to one official patch day per month apart from emergencies. As part of Windows Server 2012R2 Microsoft has released some PowerShell cmdlets do do exactly this.
Based on that TechNet article I have put together the following PowerShell script.
Get-WsusServer -Name ServerName -PortNumber 8530 | Invoke-WsusServerCleanup -CleanupObsoleteComputers -CleanupObsoleteUpdates -CompressUpdates -CleanupUnneededContentFile -DeclineExpiredUpdates -DeclineSupersededUpdates
The above command line can be copied into a file and invoked either manually or via the task scheduler. Below is a sample output.
When setting up a scheduled job you may want to redirect the output to a file. To do this simple add “| Out-File C:\Scripts\clean_wsus.log” at the end. The filename and directory can of course be changed. Here is the full script.