How to: Find stale servers in Active Directory

For any system engineer working with Active Directory or just about any IT service out there, good IT hygiene (cyber hygiene) is key to maintaining a healthy and manageable environment. For Active Directory it’s a good idea to check periodically for stale server computer objects and remove or resolve them. They might be a sign that a server was decommissioned from the company network incompletely or that a server has some communication issues with AD. One way to get an indication of this is to check the WhenChanged attribute which periodically updates for a number of reasons I will not cover here.

This can be done at scale using the below PowerShell code and expanded on for advanced reporting and additional checking.

# Set the threshold date for stale servers
$thresholdDate = (Get-Date).AddMonths(-6)

# Get all server computer objects in AD
$servers = Get-ADComputer -Filter {OperatingSystem -like "*Server*"} -Properties whenchanged

# Loop through each server and check its last update date
foreach ($server in $servers) {
    $lastUpdate = $server.WhenChanged
    if ($lastUpdate -lt $thresholdDate) {
        Write-Output "$($server.Name) hasn't been updated in AD since $($lastUpdate.ToShortDateString())"
    }
}

You May Also Like

About the Author: Phil

Leave a Reply

Your email address will not be published. Required fields are marked *