Dam Good Admin

Or at least not entirely useless

Fully Automate Software Update Maintenance in Configuration Manager

Recently I got on a kick to fully automate everything I could as it relates to software updates in Configuration Manager.  While other scripts exist I wanted that one script to rule them all.  I also wanted it to be completely PowerShell, flexible enough so that it could work in nearly every environment, and have decent logging.  I believe I’ve achieved those goals and encourage you to try it out and give me any feedback you may have:

First A Word from My Legal Department

For the love of all you hold dear, test the ever-living-crap out of this script by running it with the -WhatIf switch and pouring through the logs to understand what the script would do.  I also recommend using the UpdateListOutputFile parameter to output a comma-delimited list of updates that will be declined.  Seriously, anything you do to your organization with this script is totally not my fault.  Once an update has been declined in WSUS and synced to Configuration Manager I honestly don’t know how you bring it back.  I’m … sure … there’s a way somehow.

Edited to Add: Jon Warnken over at mrbodean.net answered the question I was too lazy to even ask. To bring back a declined update you can approve it in the WSUS (via the console or script) and then initiate a full sync.  When you sync updates from within the console you only do a delta or incremental sync so that won’t work  To fully synchronize it must be initiated by the Configuration Manager sync schedule or via a script.  John provides the few lines of codes needed to so in this blog post.  If you’re using my Invoke-DGASoftwareUpdatePointSync script to schedule the syncs after Patch Tuesday those will work as well.

What Can it Do?

The script can be used to do any or all of the following:

  • Detect if a synchronization is occurring and wait for success before resuming.
  • Decline superseded updates.
  • Decline updates by a list of titles.
  • Decline updates based on external plugin scripts.
  • Output a comma-delimited list of declined updates.
  • Run the WSUS Cleanup Wizard.
  • Initiate a software update synchronization.
  • Remove expired and declined updates from software update groups.
  • Delete software update groups that have no updates.
  • Combine software update groups into yearly groups.
  • Set the maximum run time for updates by title.
  • Remove unneeded files from the deployment package source folder.
  • Update the deployment packages used by ADRs either monthly or yearly.

What, Where, When, and How?

So it’s a bit … wordy … but here is the command line I run in my environments.  Note that copy and pasting quotation marks from the internet is fraught with error so if you run into trouble be sure to manually swap them out in notepad or the like.

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -noninteractive -Command “& ‘\\#PATH TO SCRIPT FOLDER#\Invoke-DGASoftwareUpdateMaintenance.ps1’ -UpdateListOutputFile ‘\\#PATH TO SCRIPT FOLDER#\UpdateListOutputFile.csv’ -RunCleanUpWizard -DeclineSuperseded -DeclineByTitle @(‘*Itanium*’,’*ia64*’,’*Beta*’) -DeclineByPlugins -ReSyncUpdates -CleanSUGs -RemoveEmptySUGs -CombineSUGs 3 -MaxUpdateRuntime @{‘*Security Monthly Quality Rollup For Windows*’=60;’*Security and Quality Rollup for .NET*’=60} -CleanSources -UpdateADRDeploymentPackages Yearly”

Currently this script must be ran on the primary site server as it makes certain queries to WMI classes that only reside there.  If I was a better person or developer I could probably figure it out.  Unfortunately I’m neither of those things.  In theory, when 1706 hits critical mass the newer cmdlets could allow it to be more portable but I don’t really see the value.  If you do for some reason, let me know the use case.  The user running this is going to need a lot of permissions to a bunch of things and the primary site’s system account is perfect on that front.

The script is designed to be ran between the time your Software Update Point(s) sync updates from Microsoft and when your ADRs run.  This allows the plugin scripts to preemptively decline updates that ADR selection can’t properly filter.  Nothing prevents you from running it any time you like of course.  In fact, if you have not been maintaining updates I recommend running this manually outside of your normal patching cycle first.

To make this all happen automatically, I super highly recommend you create a status filter rule that triggers based on the update synchronization ending successfully.  To do so, create a rule that runs your desired command when the SMS_WSUS_SYNC_MANAGER component sends a status with message ID 6702.  Should look a little like this:

Warning: Do NOT use the -Force parameter when creating the status filter rule if you are also using the ReSyncUpdates parameter.  That will create an infinite loop whereby the script is triggered by a synchronization and then initiates another synchronization.

Plugin Scripts You Say?

At some point someone is bound to ask ‘can it decline this’ and the answer will always be yes.  Simply take the template plugin script file I’ve provided and use it to add whatever bat-shit-crazy logic you want in order to add updates to the DeclinedUpdates hash table.  One of the key use-cases for plugin scripts is to to fill gaps in the Automatic Deployment Rule (ADR) filtering capabilities.  There’s a limit to the logic that such filters can support.  The logic you can put in a PowerShell script is only limited by your imagination, ability, and the data at hand.  By declining updates and initiating a sync before the ADRs run you can filter out updates that ADR selection cannot.  Be warned though, it is not a simple matter to bring back declined updates so there is a certain amount of risk in declining updates before you even get to see them in the Configuration Manager console.

I have provided a set of standard plugins that you can make use of.  To do so you must first move them out of the Disabled folder and into the root of the Plugins folder.  Running this set of plugins alone has declined over 900 updates in my environment. Note that some plugins will need to be edited before you can run them.

  • Decline-Office365Editions: Use this plugin script to decline Office 365 editions that you do not deploy.  If you leave the LatestVersionOnly variable at its default value of True the script will determine what the highest version is for each edition and decline older versions.  This is particularly important for editions like the Semi-Annual edition that has multiple supported versions.  You will need to un-comment and fill in the SupportedEditions array.  Any edition not listed will be declined.  This script has a variable called KnownEditions that lists all currently known editions which are matched against each title.  This will hopefully prevent the script from going awry when the Office product team decides to get drunk, bring out a dart-board, and come up with a new naming scheme.  When they do, you will have to update this variable.
  • Decline-Windows10Editions: Use this plugin script to decline Windows 10 feature updates for editions you do not support.  Like its Office 365 brethren it has the same SupportedEditions variable you will need to modify and the KnownEditions variable you may need to manage in the future.  With the release of Windows 10 version 1709 all editions are now packaged in two editions (whose updates were named exactly the same … sigh) and each duplicated for x86 and x64.  So long term I don’t think this plugin will be needed.
  • Decline-Windows10Languages: Use this plugin script to decline Windows 10 updates for languages that are not configured to download software update files in the site’s Software Update Point component.  I don’t know why the Windows 10 feature updates ignore this setting but it does and this solves that problem.  There’s nothing to configure here but if you are using ADRs or manually downloading updates for languages not configured in the component I recommend not using this plugin script.
  • Decline-Windows10Versions: Use this plugin script to decline Windows 10 updates for versions your organization no longer supports or never deployed in the first place.  This script has a variable called UnsupportedVersions that you must un-comment and enter the list of versions (ex. 1511) that you do not support.  Updates matching one of these versions will be declined.

The Results

Here’s the summary of declined updates after running this in my production environment for the first time.  This environment was around two years old at the time and had never been maintained apart from Configuration Manager’s built-in feature to run the WSUS Cleanup Wizard.

All Updates = 10921
All Updates Except Declined = 9768
All Superseded Updates = 5141
Superseded Updates Declined = 4979
Updates Declined by Title for *Itanium* = 807
Updates Declined by Title for *ia64* = 46
Updates Declined by Title for *Beta* = 7
Updates Declined by Title (Total) = 860
Updates Declined by Plugin for Decline-Windows10Languages = 312
Updates Declined by Plugin for Decline-Windows10Versions = 38
Updates Declined by Plugin for Decline-Windows10Editions = 496
Updates Declined by Plugin for Decline-Office365Editions = 58
Updates Declined by Plugin (Total Unique) = 904
Total Newly Declined Updates = 6435
Total Active Updates = 3333

You’re reading that right.  By running this script I have reduced the number of updates every single device in my organization scans against from 9,768 to 3, 333 … a 66% reduction.  That’s the kind of thing that makes a huge difference in terms of WSUS and Windows Update Agent performance.  It’s enough to be the difference between success and failure.


I have only tested this script on Current Branch 1702 and above.  Some or all of the script may work on earlier versions but I don’t have the resources or inclination to create that many test environments.

The WSUS console and cmdlets must be installed.

The Configuration Manager console and cmdlets must be installed.

The script must be ran on or from the primary site server.

The user needs to be part of the WSUS Administrators group on SUPs.

The user needs full access to the deployment package source folders.

The user needs the appropriate rights in SCCM to modify the objects your chosen parameters will impact.

So yea … run this as the primary server’s system account.  Use psexec /s /i cmd.exe to do so.

The Parameters

Every parameter listed below is optional but you must select at least one of the action parameters for the script to do anything.  I have provided extensive documentation within the script itself and running Get-Help should really be all you need.  But you’re lazy.  I’m lazy.  We’re all basically lazy.  So here you go:

-FirstRun [switch]

If your environment or a the environment of a close ‘friend’ has never been maintained and the script times out when ran then run the script manually one time using this option.  It will connect directly to the WSUS database (SUSDB) and get a list of obsolete updates using the spGetObsoleteUpdatesToCleanup stored procedure.  It then loops through and deletes each one using the spDeleteUpdate stored procedure.  This mimics what the WSUS cleanup wizard does but with a 30 minute timeout instead of the default 30 second one.  Be aware that this may take hours, days, weeks, or even longer to complete.  However, it most likely will complete unlike the wizard. Afterwards you should be able to run the script normally.

-DeclineSuperseded [switch]

Declines updates that are superseded in WSUS.  Refer to the DeclineLastLevelOnly and ExclusionPeriod parameters for options regarding which superseded update you decline.

-DeclineLastLevelOnly [switch]

Only declines updates that do not supersede other updates.  Must be used with the DeclineSuperseded parameter.  Honestly, I have no idea why you want to use this but I put this in for completeness as compared to other scripts.

-ExclusionPeriod [int]

An integer that controls how many months to wait before declining a superseded update.  Must be used with the DeclineSuperseded parameter and only impacts updates declined by that parameter.  If this parameter is not defined then the script will use the exclusion period configured in the Software Update component for declining superseded updates.

-DeclineByTitle [string[]]

Provide an array of titles that will be used to decline updates in WSUS.  Wildcards are of course supported.  Note that passing in an array via the command line is a bit tricky and you must use the -command option when using this parameter.  See the example above for how to do this.

-DeclineByPlugins [switch]

Loop through every PowerShell script file (.PS1) in the Plugins folder relative to the script and call its Invoke-SelectUpdatesPlugin function.  This allows users to decline updates using whatever logic they desire.  The download includes some examples as well as a template to build from.  In order to use the provided plugin scripts you will need to copy them from the Disabled folder into the root of the Plugins folder.  Some of them need to be edited before they are ran.  See the Plugin Script section above above for more details.

-UpdateListOutputFile [string]

Specify a file path where the script will output a comma delimited text file listing the details of every update it declines and the reason why it was declined.

-RunCleanupWizard [switch]

Runs the WSUS Cleanup Wizard with all the options selected after declining updates.  Even though Configuration Manager includes this feature now I’ve included this for completeness.  To be honest, I’m not certain what Configuration Manager is actually doing on this front.  I’ve had the built-in feature enabled from day one and yet when I ran this manually in my environments the first cleanup run took 1-2 hours and cleaned up thousands of items.  Subsequent runs took minutes.  As an added bonus it will write the results to the log file.

-LogFile [string]

Specify an alternate log file path.  By default the script will create the log in the same folder as the script.

-MaxLogSize [int]

Specify the maximum size of the log file before it rolls over and rename the current log with the ‘.lo_’ extension.  The default is 2 MB.

-SyncLeadTime [int]

Specifies the number of minutes to wait after a software update synchronization has occurred before continuing script execution.  The default is 5 minutes.

-Force [switch]

The script creates an empty file in the its directory to mark the last time it ran and will not run again if that file is newer than 24 hours unless the Force parameter is used.  Be very very careful with this parameter.  If used in conjunction with the ReSyncUpdates parameter as part of a status filter rule you can create a forever loop.

-ReSyncUpdates [switch]

Initiate a full Configuration Manager software update synchronization.  This will run after the updates have been declined in WSUS and will expire the declined updates in Configuration Manager.

-CleanSUGs [switch]

Loop through every Software Update Group and remove any expired or newly declined updates.

-RemoveEmptySUGs [switch]

Remove any Software Update Groups that do not contain any software updates.  Must be used with the CleanSUGs parameter.

-CombineSUGs [int]

Combine Software Updates Groups so that only the provided number of groups exist per Automatic Deployment Rule.  The first group created for a given year will be renamed by having its timestamp truncated to just its year and will have the remaining groups updates added to it.

-MaxUpdateRuntime [hashtable]

Provide a hash-table where the keys are titles and the values are the number of minutes to set matching updates’ maximum run-time to.  Wildcards are of course supported for the titles.  Note that passing in a hash-table via the command line is a bit tricky and you must use the -command option when using this parameter.  See the example above for how to do this.

-CleanSources [switch]

Loop through the software update Deployment Packages and remove any sub-folders whose name does not match a GUID of an update in the package.

-UpdateADRDeploymentPackages [string (‘Yearly’,’Monthly’)]

Update Automatic Deployment Rules to use the appropriate software update Deployment Package and create a new package when necessary.  Valid values are ‘Yearly’ or ‘Monthly’.  When used, the name of the deployment package and the source folder for the package must end with four digits that represent the desired period.  For yearly packages a four-digit year (ex. 2017) must be used and for monthly packages use YYMM (ex. 1710 for October 2017).

-SiteCode [string]

Provide the site code of the site you wish to connect to.  By default the script will try to identify the site by the PS-Drives available or from the registry.  In environments with a CAS this parameter must be provided.

-StandAloneWSUS [string]

If you wish to run the script against a stand-alone WSUS server then specify the FQDN of the WSUS server using this parameter.  When doing so the script will prevent you from also including parameters that only apply to a Configuration Manager environment.

-StandAloneWSUSSSL [switch]

If you specified the StandAloneWSUS parameter you may optionally specify whether to connect via SSL or not.  If this parameter is not used the script will try to connect without using SSL.

-StandAloneWSUSPort [int]

If you specified the StandAloneWSUS parameter you may optionally specify the port to connect upon.  If not specified the port will default to 8531 if the StandAloneWSUSSSL switch is used and 8530 if it is not.

-WhatIf [switch]

Last, but not least, use this to test what the script will do without making any changes.  Refer to the log or use the UpdateListOutputFile  parameter to output a list of declined updates.



  1. Hi there
    Thanks for sharing this great script. There is a small error in two lines where the percentcomplete is calculated. If you remove the “* 100” it works great. Otherwise you get errors about the percent complete going over 100 in the write-progress function.

  2. Hi Bryan,
    great post and script, even for a PS Newbie like me.
    I checked out the script and ran with the -whatif switch to see the number of obsolete updates that would be removed – returning 2667 updates.
    Then all it says in the log file is Attempting to delete update 96183 (1/2667 but how can I match that update inside SCCM to see what update it is and if it is really obsolote. I do not find any reference between number 96183 and a specific update.

    Thanks for all your hard work and making life less complicated for other people.

    • Sorry, I really gotta fix the comment notification. It’s on my to-do list post-MMS but I couldn’t find a quick way to relate the ID used by the stored procedures to an actual update.

  3. Hi Bryan,

    I keep getting the error “The software update point [redacted] failed its last synchronization with error code 2148734217. Synchronize successfully before running Invoke-DGASoftwareUpdateMaintenance.”

    But I don’t see my synchronizations failing. Have you seen this error come up before?

    • Bryan Dam

      April 11, 2018 at 1:09 pm

      That means that the LastSyncErrorCode property of one of your SUP’s SMS_SUPSyncStatus WMI class lists a non-zero value (2148734217). Could just be a disconnect between WMI and the console. Have you tried running another sync? Do that and if it continues use WMIExplorer to check out that server’s record in the SMS\site_###\SMS_SUPSyncStatus class.

  4. Hello 🙂 Thank you up front for your work and your insights! It’s helping me understand some things better, and re-affirming that the world still ‘makes sense’ (regarding IT that is).
    One question though; How long should this run? I’ve started the script, and the logs have enumerated superseeded stuff etc, but stops at “Starting Cleanup Script”….
    The PS1 is still running though; Can that be the case? Or is there something broken 🙂

    Thank you in advance!

  5. Hi Bryan,
    We’re getting the following error:
    Failed to connect to the active software update point on port
    Error: Method invocation failed because [Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlArrayItems] doesn’t contain a method named ‘Where’.
    At C:\Scripts\Rasmus\Invoke-DGASoftwareUpdateMaintenance.ps1:576 char:5
    + $ActiveSoftwareUpdatePointName = ((Get-CMSoftwareUpdatePointComponent).Props …

    Any ideas of what the issue is?

  6. Well done! Thank you for this community contribution, Bryan.

  7. DGA, you are my hero. This is extremely helpful.

    I have a question about the relationship between ADRs and Deployment Packages. Let’s say I have a package for Patch Tuesday for Windows 10 clients with a handful of products. If I’m aggressively expiring, declining and superseding AND using the CleanSources parameter, I don’t know if I see a reason to ever break apart the Deployment Packages into monthly packages. I’m new to all this so I’m expecting that I’ve overlooked something. Is this something you’d do for performance reasons or for operational sanity?

    • Bryan Dam

      December 7, 2017 at 10:57 am

      The key is to remember that the purpose of Deployment Packages is only … only … for content distribution of the update binaries or installers. They are totally unrelated to Software Update Groups or deployments. As such, there’s no technical reason to have more than one deployment package … technically one package can and will hold every update binary ever released. Practically speaking though, your DPs need to handle the validation of that package and packages can and therefore will go sideways on you forcing you to recreate them. The chance of a deployment package corrupting itself and the impact of recreating it is tied directly to the number of updates or the size of the deployment package. So most organizations, mine included, usually create a new deployment package yearly. Doing so manually isn’t hard and on a yearly basis it’s almost hardly worth automating but if you don’t then it’s a small manual task that will be forgotten. One downside to using the same deployment package each month is that you can’t stagger how that data is distributed. The source is essentially updated and all the DPs are going to try to get it immediately. If your organization needs to stagger the content distribution you might consider creating monthly deployment packages and add DPs or DP Groups over a period of time either manually or some other automation. To be clear, that’s a pretty edge use case but I figured that those using monthly SUGs are the ones who could most benefit from the UpdateADRDeploymentPackages option.

  8. Hey, It was nice seeing you at the NSCUG as a presenter. This script has work wonders. Tested this in my homelab and in production. Everything from the customized plugins to dumping the logs into something readable. You have seriously saved a lot of professionals some serious time with this and couldn’t thank you enough.

    • Thanks for the kinds word Brandon, I had a lot of fun presenting. I’m also glad to hear you are getting some use out of the script.

  9. I am getting an error of:
    Key cannot be null.
    Parameter name: key
    At C:\Scripts\Invoke-DGASoftwareUpdateMaintenance.ps1:1120 char:127
    + … .UpdateID)). Source: $($DeclinedUpdates.(Update.Id.UpdateID Error: …

    • Bryan Dam

      November 30, 2017 at 4:46 pm

      That was an failure in the error logging for the CleanSources routine. I’ve uploaded a new version which should resolve the error logging so try it again. My expectation is though that you’ll now get the actual error going on so let me know what it is. Honestly, in all my testing I never saw that section of code do much of anything. It’s only there for completeness … Configuration Manager really should be doing a good job of cleaning those out already.

Leave a Reply

© 2018 Dam Good Admin

Theme by Anders NorenUp ↑