PowerShell: Automated WSUS Maintenance (Update 1.6)

In a previous post I wrote about some configuration tweaks to improve the performance of your WSUS server. I also included a short PowerShell script to automate the WSUS maintenance process. I’ve improved the script somewhat since then, adding more configuration options. This post will serve as a change log and documentation page.

My WSUS Maintenance script can be downloaded from the Microsoft TechNet Gallery and the PowerShell Gallery.

Features and Requirements

  • The script will run the WSUS server cleanup process, which will delete obsolete updates, as well as declining expired and superseded updates.
  • It can optionally create a log file and email the log file to an address of your choice.
  • The script can be run locally on a WSUS server, or on a remote sever.
  • The script requires that the WSUS management tools be installed.
  • The script has been tested on Windows 10 and Windows Server 2016.

Generating an encrypted password file

If you’ve used a previous version I’ve changed how the script handles configuring a password for the log notification e-mail. Specifically the password must now be in an encrypted text file. The advantage of this is that the password will no longer be in plain text, which is a security risk. The downside is that you will now need to generate a password file. The command to do this is pretty simple, but it must be generated on the computer the script will be running on, and as the user used to run the script.

To generate the password file, run the following command in PowerShell. When running the command you will be prompted for a username and password. The username doesn’t matter and can be anything, but the password must be the password you want to use to authenticate to your SMTP server.

$creds = Get-Credential
$creds.Password | ConvertFrom-SecureString | Set-Content c:\scripts\ps-script-pwd.txt

After running the commands, you should have a text file contained the encrypted password. Enter the path and filename for the -pwd switch to configure authenticated e-mail notification.

Configuration

The configuration of the script can be done via command line switches. Here’s a list of all the switches and example configurations.

Command Line Switch Mandatory Description Example
-server Yes The WSUS server that should be cleaned. wsus01
-port Yes The port that the WSUS service is running on. 8530
-l No Location to store the optional log file. The name of the log file is generated automatically. E:\scripts
-sendto No The email address to send the log file to.

*This switch isn’t mandatory but is required if you wish to email the log file.

me@contoso.com
-from No* The email address that the log file should be sent from.

*This switch isn’t mandatory but is required if you wish to email the log file.

wsus@contoso.com
-smtp No* SMTP server address to use for the email functionality.

*This switch isn’t mandatory but is required if you wish to email the log file.

mail01.contoso.com

OR

smtp.live.com

OR

smtp.office365.com

-user No* The username of the account to use for SMTP authentication.

*This switch isn’t mandatory but may be required depending on the configuration of the SMTP server.

example@contoso.com
-pwd No* The location of the file containing the encrypted password of the account to use for SMTP authentication.

*This switch isn’t mandatory but may be required depending on your SMTP server.

c:\scripts\ps-script-pwd.txt
-usessl No* Add this option if you wish to use SSL with the configured SMTP server.

Tip: If you wish to send email to outlook.com or office365.com you will need this.

*This switch isn’t mandatory but may be required depending on the configuration of the SMTP server.

N/A

Change Log

16/10/2017 1.6

  • Changed SMTP authentication to require an encrypted password file.
  • Added instructions on how to generate an encrypted password file.

07/10/2017 1.5

  • Added necessary information to add the script to the PowerShell Gallery.

25/09/2017 1.4

  • Cleaned up formatting, minor changes to code for efficiency.

11/08/2017 1.3

  • Improved, cleaner logging. The log file is no longer produced from PowerShell’s Transcript function.

22/07/2017 1.2

  • Improved commenting on the code for documentation purposes.
  • Added authentication and SSL options for e-mail notification.

22/05/2017 1.1

  • Added configuration via command line switches.

PowerShell Code


<#PSScriptInfo .VERSION 1.6 .GUID 56dc6e4a-4f05-414c-9419-c575f17f581f .AUTHOR Mike Galvin twitter.com/digressive .COMPANYNAME .COPYRIGHT (C) Mike Galvin. All rights reserved. .TAGS WSUS Windows Server Update Services Maintenance Clean up .LICENSEURI .PROJECTURI https://gal.vin/2017/08/28/automate-wsus-maintenance .ICONURI .EXTERNALMODULEDEPENDENCIES WSUS Management PowerShell module. .REQUIREDSCRIPTS .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES #>

<# .SYNOPSIS Runs the maintenance/clean up routine for WSUS. .DESCRIPTION Runs the maintenance/clean up routine for WSUS. This script will: Run the WSUS server clean up process, which will delete obsolete updates, as well as declining expired and superseded updates. It can also optionally create a log file and email the log file to an address of your choice. Please note: to send a log file using ssl and an SMTP password you must generate an encrypted password file. The password file is unique to both the user and machine. The command is as follows: $creds = Get-Credential $creds.Password | ConvertFrom-SecureString | Set-Content c:\foo\ps-script-pwd.txt .PARAMETER Server The WSUS server to run the maintenance routine on. .PARAMETER Port The port WSUS is running on. .PARAMETER L The path to output the log file to. The file name will be Wsus-Maintenance.log .PARAMETER SendTo The e-mail address the log should be sent to. .PARAMETER From The from address the log should be sent from. .PARAMETER Smtp The DNS name or IP address of the SMTP server. .PARAMETER User The user account to connect to the SMTP server. .PARAMETER Pwd The password for the user account. .PARAMETER UseSsl Connect to the SMTP server using SSL. .EXAMPLE Wsus-Maintenance.ps1 -Server wsus01 -Port 8530 -L E:\scripts -SendTo me@contoso.com -From wsus@contoso.com -Smtp smtp.contoso.com -User me@contoso.com -Pwd P@ssw0rd -UseSsl This will run the maintenance on the WSUS server on wsus01 hosted on port 8530. A log will be output to E:\scripts and e-mailed via a authenticated smtp server using ssl. #>

[CmdletBinding()]
Param(
    [parameter(Mandatory=$True)]
    [alias("Server")]
    $WsusServer,
    [parameter(Mandatory=$True)]
    [alias("Port")]
    $WsusPort,
    [alias("L")]
    $LogPath,
    [alias("SendTo")]
    $MailTo,
    [alias("From")]
    $MailFrom,
    [alias("Smtp")]
    $SmtpServer,
    [alias("User")]
    $SmtpUser,
    [alias("Pwd")]
    $SmtpPwd,
    [switch]$UseSsl)

## If logging is configured, start log
If ($LogPath)
{
    $LogFile = "Wsus-Maintenance.log"
    $Log = "$LogPath\$LogFile"

    ## If the log file already exists, clear it
    $LogT = Test-Path -Path $Log
    If ($LogT)
    {
        Clear-Content -Path $Log
    }

    Add-Content -Path $Log -Value "****************************************"
    Add-Content -Path $Log -Value "$(Get-Date -Format G) Log started"
    Add-Content -Path $Log -Value ""
}

## Logging
If ($LogPath)
{
    Add-Content -Path $Log -Value "$(Get-Date -Format G) WSUS maintenance routine starting..."
    Add-Content -Path $Log -Value ""
}

## Get the WSUS server configured and perform the maintainence operations
$WsusMaintCmd = Get-WsusServer | Invoke-WsusServerCleanup -CleanupObsoleteComputers -CleanupObsoleteUpdates -CleanupUnneededContentFiles -CompressUpdates -DeclineExpiredUpdates -DeclineSupersededUpdates

Get-WsusServer -Name $WsusServer -PortNumber $WsusPort

## Logging
If ($LogPath)
{
    $WsusMaintCmd | Out-File -Append $Log -Encoding ASCII
}

Else
{
    $WsusMaintCmd
}

## If log was configured stop the log
If ($LogPath)
{
    ## If log was configured stop the log
    Add-Content -Path $Log -Value ""
    Add-Content -Path $Log -Value "$(Get-Date -Format G) Log finished"
    Add-Content -Path $Log -Value "****************************************"

    ## If email was configured, set the variables for the email subject and body
    If ($SmtpServer)
    {
        $MailSubject = "WSUS Maintenance"
        $MailBody = Get-Content -Path $Log | Out-String

        ## If an email password was configured, create a variable with the username and password
        If ($SmtpPwd)
        {
            $SmtpPwdEncrypt = Get-Content $SmtpPwd | ConvertTo-SecureString
            $SmtpCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($SmtpUser, $SmtpPwdEncrypt)

            ## If ssl was configured, send the email with ssl
            If ($UseSsl)
            {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -UseSsl -Credential $SmtpCreds
            }

            ## If ssl wasn't configured, send the email without ssl
            Else
            {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Credential $SmtpCreds
            }
        }
    
        ## If an email username and password were not configured, send the email without authentication
        Else
        {
            Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer
        }
    }
}

## End

If you’d like to get in touch with me please leave a comment or tweet me.

-Mike

Follow Mike on Twitter: @Digressive

5 thoughts on “PowerShell: Automated WSUS Maintenance (Update 1.6)

    1. Hi Cory,
      I’ve not tested it on a SCCM installation with WSUS, but I see no reason why it shouldn’t work. As as I understand it WSUS is essentially the same, even when it is installed with SCCM.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s