Cleanup WSUS – Remove Computers No Longer in the Domain

One thing I love about WSUS is the ability to monitor the presence of clients. It gives me a good approximation of the last time a computer was on the network. I often use this information to help me clean missing computers out of Active Directory.

But what about when a computer is removed from the domain before it is removed from WSUS? Rather than manually checking, I wrote an IronPython script that compares the list of computers in Active Directory with the computers on WSUS. When I run this script, it lists computers that should be removed from WSUS, and deletes them for me (after prompting).

Below is a copy of the script. It is written in Python, and I run it using IronPython 2.0 Release Candidate 1.
It requires the WSUS 3.0 API, specifically
Microsoft.UpdateServices.Administration.dll. As long as that library is
available, the script doesn’t need to be run on the server itself.

def WsusComputers():
  """Load computers from WSUS"""
  import clr
  import Microsoft.UpdateServices.Administration
  computers     = dict()
  wsus          = Microsoft.UpdateServices.Administration.AdminProxy.GetUpdateServer('WSUS-SERVER-NAME-HERE', False)
  computerScope = Microsoft.UpdateServices.Administration.ComputerTargetScope()
  for computer in wsus.GetComputerTargets(computerScope):
    name = computer.FullDomainName.lower()
    computers[name] = computer
  return computers
def AdComputers():
  """Load computers from Active Directory"""
  import clr
  import System.DirectoryServices
  computers = dict()
  entry     = System.DirectoryServices.DirectoryEntry('')
  searcher  = System.DirectoryServices.DirectorySearcher(entry)
  searcher.Filter   = '(&(objectcategory=computer)(objectClass=computer))'
  searcher.PageSize = 250
  for computer in searcher.FindAll():
    if computer.Properties.Contains('dnshostname'):
      name = computer.Properties['dnshostname'][0]
      if name != None: computers[name.lower()] = computer
  return computers
def Cleanup():
  """Delete computers from WSUS that are not in active directory"""
  print 'Loading WSUS computers...'
  wsus = WsusComputers()
  print wsus.Count, 'computers loaded.'
  print ''
  print 'Loading AD computers...'
  ad   = AdComputers()
  print ad.Count, 'computers loaded.'
  print ''
  """Identitify computers that are not in active directory"""
  missing = [computer for name, computer in wsus.iteritems() if not ad.Contains(name)]
  print missing.Count, 'computers to be removed'
  for computer in missing: print computer.FullDomainName
  print ''
  """Delete computers that are not in active directory"""
  if missing.Count > 0 and raw_input('Delete? (Y/N): ').lower().startswith('y'):
    for computer in missing:
      print 'Deleting', computer.FullDomainName
raw_input("Press any key to continue")


This script is released free of charge to do with as you please.