Tuesday, October 29, 2019

PowerShell: Script to automate the cleaning of the WSUS update server

The launch of this script can be set in the task scheduler and no longer worry about the need to periodically clean up the WSUS server.

$WsusServer = "wsus.mycompany.corp"
$UseSSL = $false
$PortNumber = 80

#E-mail Configuration
$SMTPServer = "smtp.mycompany.corp"
$FromAddress = "WSUS@mycompany.corp"
[string[]] $Recipients = "admin1@mycompany.corp", "admin2@mycompany.corp", "admin3@mycompany.corp"
$MessageSubject = "WSUS :: CleanUP WSUS Server"

Function SendEmailStatus($MessageSubject, $MessageBody)
{
$SMTPMessage = New-Object System.Net.Mail.MailMessage
$SMTPMessage.from = $FromAddress
foreach($recipient in $Recipients)
{
$SMTPMessage.to.Add($recipient)
}
$SMTPMessage.Subject = $MessageSubject
$SMTPMessage.Body = $MessageBody
$SMTPMessage.IsBodyHTML = $true
#Send the message via the local SMTP Server
$SMTPClient = New-Object System.Net.Mail.SMTPClient $SMTPServer
$SMTPClient.Send($SMTPMessage)
$SMTPMessage.Dispose()
rv SMTPClient
rv SMTPMessage
}

if($UseSSL){$wsus = Get-WsusServer -UseSsl -Name $WsusServer -PortNumber $PortNumber}
else {$wsus = Get-WsusServer -Name $WsusServer -PortNumber $PortNumber}
$MessageBody = $wsus | Invoke-WsusServerCleanup -CleanupObsoleteComputers `
-CleanupObsoleteUpdates -CleanupUnneededContentFiles -CompressUpdates `
-DeclineExpiredUpdates -DeclineSupersededUpdates
$MessageBody = $MessageBody `
-replace "\d{0,3}\s{0,1}(\D*):\s{0,1}(\d)*",'<tr><td>$1&nbsp;&nbsp;</td><td><b>$2</b></td></tr>'
$MessageBody = '<table>' + $MessageBody + '</table>'
SendEmailStatus $MessageSubject $MessageBody

Before you start using, you must set the constants according to your infrastructure. More specifically, this: the server name, port, the flag for using the SSL protocol, the SMTP server for sending the report, the sender and recipients addresses, the subject of the letter.

No comments:

Post a Comment