Document created by Yakov Goldberg
UBSERC TEAM
Our website: http://www.ubersec.com
Follow Us in Twitter: http://twitter.com/#!/ubersec
WSUS server database clean-up Powershell script
Background
Many organizations utilize Windows Server Update Services (WSUS) server to centralize Windows updates and distribute them to all client machines that run Windows Operating Systems (OS) accordingly. On many occasions however, WSUS server will keep downloading updates from Microsoft for a variety of products and keep these updates in the hard-drive until the administrator decides to run the Server Cleanup Wizard manually from the Options tab in Update services. Yet, the administrator must always remember to execute that option manually or otherwise, WSUS server will keep downloading new updates while keeping older updates in the system. Thus, the server will get filled up with more and more updates until the hard-disk have reached full capacity. To help and reduce the likelihood for something like as such to occur, administrator can utilize Powershell WSUS clean-up script to clean older updates from WSUS server automatically. The following instructions will show administrator how to create a Powershell script that cleans up older updates (older than 30 day or unapproved updates) and then send the recipient (usually the administrator) an email with the results.
Keep in mind that for the script to work properly you will need your email server (usually exchange) to be an open-relay server. From a security perspective, this is not an always a good thing to have an email open-relay server since malicious attackers can find out the Internet Protocol (IP) of your email server and use it to send emails on the behalf of your company since your email server is open-relay server. My script is basic and doesn’t contain any security features in mind. Feel free to tweak or modify the script to enforce more security and authentication to your email server by creating a special account for that script in Active Directory (AD).
Operating Systems:
The script has been tested in the following OS:
- Windows 2003
- Windows 2008
- Windows 2008 R2
With
- WSUS version 2 and 3
Instructions
First and foremost you must assure that PowerShell 2.0 is installed and running on your WSUS Server. To do that, please go to your command line and type:
powershell
If you windows have lunched Powershell you should see the letters
PS next to the prompt line (look above). If Windows does not recognize the command “powershell”, you will have to download the Windows Management Framework Core (WinRM 2.0 and Windows Powershell 2.0) and install is on your Wsus server from the following link:
Once you have downloaded and completed the Powershell (PS) installation on your wsus server, you will need to set Powershell restriction policy level to
Unrestricted. To do that, type the followings
Set-ExecutionPolicy Unrestricted in your command line:
PS C:\> Set-ExecutionPolicy Unrestricted
Setting the execution policy level to unrestricted allow the user to execute Powershell scripts on the system. Keep in mind that setting the policy to unrestricted is not always a good idea since you allow your server to execute any PS script. Thus, attackers could run their scripts on that server as well if they were ever successful gaining access to the server. For more information about the PS Execution policy please refer to the following link:
Now you should be able to copy and paste the following script to your notepad and change server variables such as the
From and
To addresses and your Fully Qualified Domain Name (FQDN) of your WSUS server and your Exchange server (or any other email server you may be using).
#Region VARIABLES
# WSUS Connection Parameters:
## Change settings below to your situation. ##
# Enter your FQDN of the WSUS server
[String]$parentServer = "wsusserver.ubersec.com"
# Use secure connection $True or $False
[Boolean]$useSecureConnection = $False
[Int32]$portNumber = 80
# From address for email notifications. You can name it to whatever you want.
[String]$emailFromAddress = WsusAdmin@ubersec.com
# To address for email notifications. The recipient whom needs to receive emails upon the cleanup completion.
[String]$emailToAddress = uberadmingroup@ubersec.com
# Subject of email notification
[String]$emailSubject = "WSUS Cleanup Results"
# Enter your FQDM for Exchange server
[String]$emailMailserver = "emailmxsrv.ubersec.com"
# Cleanup Parameters:
## Set to $True or $False ##
# Decline updates that have not been approved for 30 days or more, are not currently needed by any clients, and are superseded by an approved update.
[Boolean]$supersededUpdates = $True
# Decline updates that aren't approved and have been expired my Microsoft.
[Boolean]$expiredUpdates = $True
# Delete updates that are expired and have not been approved for 30 days or more.
[Boolean]$obsoleteUpdates = $True
# Delete older update revisions that have not been approved for 30 days or more.
[Boolean]$compressUpdates = $True
# Delete computers that have not contacted the server in 30 days or more.
[Boolean]$obsoleteComputers = $True
# Delete update files that aren't needed by updates or downstream servers.
[Boolean]$unneededContentFiles = $True
#EndRegion VARIABLES
#Region SCRIPT
# Load .NET assembly
[void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration");
# Connect to WSUS Server
$wsusParent =
[Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($parentServer,$useS
ecureConnection,$portNumber);
# Log the date first
$DateNow = Get-Date
# Perform Cleanup
$Body += "$parentServer ($DateNow ) :" | Out-String
$CleanupManager = $wsusParent.GetCleanupManager();
$CleanupScope = New-Object
Microsoft.UpdateServices.Administration.CleanupScope($supersededUpdates,$expiredUpdates
,$obsoleteUpdates,$compressUpdates,$obsoleteComputers,$unneededContentFiles);
$Body += $CleanupManager.PerformCleanup($CleanupScope) | Out-String
#Get list of downstream servers
$wsusDownstreams =
[Microsoft.UpdateServices.Administration.AdminProxy]::DownstreamServerCollection;
$wsusDownstreams = $wsusParent.GetDownstreamServers();
#Clean each downstream server
$wsusDownstreams | ForEach-Object {
$ping = New-Object System.Net.NetworkInformation.Ping
$DSServer = $_.FullDomainName
Try{
$Reply = $ping.send($DSServer)
$ReplyStatus = $Reply.Status
Write-Host $ReplyStatus
}
catch{
$ReplyStatus = "False"
Write-Host $ReplyStatus
}
if ($ReplyStatus -eq "Success")
{
# Log the date first
$DateNow = Get-Date
$Body += $DSServer + " ($DateNow ) : " | Out-String
$wsusReplica =
[Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($_.FullDomainName,
$useSecureConnection,$portNumber);
$CleanupManager = $wsusReplica.GetCleanupManager();
$CleanupScope = New-Object
Microsoft.UpdateServices.Administration.CleanupScope($supersededUpdates,$expiredUpdates
,$obsoleteUpdates,$compressUpdates,$obsoleteComputers,$unneededContentFiles);
$Body += $CleanupManager.PerformCleanup($CleanupScope) | Out-String
}else{
# Log the date first
$DateNow = Get-Date
$Body += $DSServer + " ($DateNow ) : not pingable`n" | Out-String
}
}
# Send the results in an email
#Send-MailMessage -From $emailFromAddress -To $emailToAddress -Subject $emailSubject -Body $Body -SmtpServer $emailMailserver
# Mail the report...
$message = new-object Net.Mail.MailMessage
$mailer = new-object Net.Mail.SmtpClient($emailMailserver)
# From address for email notifications. You can name it to whatever you want.
$message.From = wsusadmin@ubersec.com
# To address for email notifications. The recipient whom needs to receive emails upon the cleanup completion.
$message.To.Add("uberadmingroup@ubersec.com ")
$message.Subject = "Windows Update - Server Clean-Up Wizard"
$message.Body = ($Body)
$mailer.Send($message)
#EndRegion SCRIPT
#You are done!
Don't forget that you will have to change the MX server FQDN and the WSUS server FQDN in the lines at the top of the script. In addition, you will also have to add the [TO] and [FROM] email addressees.
You can also download the script and modify the lines that say
”Change me” for your convenience from the following link:
Now you can setup a scheduled job on your WSUS server to run that script once a week. Keep in mind that if you have Windows 2003 server you may not be able to run a Powershell scripts directly as a scheduled tasks. Rather, you will need to create a batch file that execute that script and then run that batch file in the schedule. The content of the batch file should look as the followings:
@echo off
cls
powershell c:\>Wsus_script.ps1
Once the batch file is executed, it will execute the Powershell script and once this process is completed, your Admin group should receive an email that looks as the followings:
wsusserver.ubersec.com (01/01/2012 02:01:39 ) :
SupersededUpdatesDeclined : 0
ExpiredUpdatesDeclined : 0
ObsoleteUpdatesDeleted : 0
UpdatesCompressed : 79
ObsoleteComputersDeleted : 0
DiskSpaceFreed : 0
If successful, you are done!