As time goes on, the computer accounts in your AD could be getting quite messy. More and more computer accounts became obsolete as their physical counterpart gets disposed. At one point, a cleaning job is due to be performed to clean up the mess. There are probably a lot of ways but here is a PowerShell way that is pretty easy to follow and execute.
One way to determine a computer account is obsolete is to find when it was logged on last time. If it hasn’t been logged in for a year, the chances that the computer is no longer in service is pretty high. So, let’s use the cmdlet Get-ADComputer with a filter to get a list of computers that haven’t been logged in for a year.
$oneyear = (Get-Date).AddDays(-365) Get-ADComputer -Filter {LastLogonDate -lt $oneyear}
To get a cleaner list, we can specify which properties to display and sort as well.
$oneyear = (Get-Date).AddDays(-365) Get-ADComputer -Filter {LastLogonDate -lt $oneyear} | Select-Object Name, LastLogonDate | Sort-Object Name
We can also export the result to a CSV file to verify. Then we can feed the list to Remove-ADComputer cmdlet to remove the accounts from the Active Directory.
$oneyear = (Get-Date).AddDays(-365) Get-ADComputer -Filter {LastLogonDate -lt $oneyear} | Select-Object Name, LastLogonDate | Sort-Object Name | ConverTo-CSV -NoTypeInformation > c:\temp\obsolete.csv
Thanks to Charlie Russel for the tip.