One of the things that I find time, and time again, when I join an organisation, is that there is a HUGE multitude of old computer accounts left littering Active Directory.  Though it might not seem like a big problem, this creates an asset and security management overhead that is really unnecessary.  Here’s some cool PowerShell that you can schedule to run an automated clean up on a regular basis.
It is preferable to disable old computer accounts rather than delete them straight away, as one of them will invariably come out of the woodwork at some stage.  Deleting the computer account will require re-joining them to the domain, whereas a disabled account can be instantly re-enabled ready to go.
What I normally do is:
  • Identify Computer Accounts that have been inactive for over 6 months (180 days) in a particular OU
  • Disabled the accounts
  • Update the Computer Description to show that it was disabled and when it can be safely deleted (usually a month later)
  • Move them to a separate OU that I’ve created (_Disabled Accounts, in this case)
  • Document that they have been disabled to file
The Script
import-Module ActiveDirectory
$date = get-date
$results = @()
$expiryDate = (get-date).AddDays(31)
$systems = Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan "-180" -SearchBase "OU=Workstations, OU=Dave Lab, DC=davelab, DC=local" | Where {$_.Enabled -eq $true}
if ($systems)
   {
      foreach($computer in $systems)
      {
         $results += $computer | select-object Name, OperatingSystem, DistinguishedName, LastLogonTimeStamp
         $computer | disable-ADaccount
         $computer | Set-ADComputer -Description "Disabled on $date. Can be deleted safely after $expiryDate"
         $computer | move-ADobject -targetpath  "OU=_Disabled Accounts, OU=Workstations, OU=Dave Lab, DC=davelab, DC=local"
         write-host "$computer has been disabled and moved."
      }

      $dateForFilename = $date.ToShortDateString() | foreach {$_ -replace "/", ""}
      $results | export-csv "C:\Scheduled Tasks\AD Cleanup\$dateForFilename - Inactive Computers Check.csv" -NoTypeInformation

   }

else
   {
      write-host No inactive and enabled computer accounts found.
   }

Set this to run as a scheduled task (say once a month), and it will go through and cleanup your stale AD Computer Accounts, move them to a centralised disabled accounts OU, and write you a log file and description on the object so you know when it was deleted.

error: Content is protected !!