
Finding expired computers in AD
As domains grow and change, one of the largest polluters of AD is expired machine accounts. Whenever a computer is joined to the domain, a machine account is created. However, when a machine is retired, the machine account is often left. There are no built-in tools to remove these machine accounts from the domain, and unlike user accounts, they are rarely audited. This becomes a problem as the environment grows, and auditing of the computer accounts becomes difficult.
This recipe will show how to search AD for expired, or nearly expired, machine accounts.
How to do it...
Carry out the following steps to find expired computers in AD:
- To find recently aged accounts execute the following code:
$30Days = (Get-Date).AddDays(-30) Get-ADComputer -Properties lastLogonDate -Filter 'lastLogonDate -lt $30Days' | Format-Table Name, LastLogonDate
- To find older accounts execute the following code:
$60Days = (Get-Date).AddDays(-60) Get-ADComputer -Properties lastLogonDate -Filter 'lastLogonDate -lt $60Days' | Format-Table Name, LastLogonDate
How it works...
By default, machine accounts are reset every 30 days, regardless of the user password expiration policy. With this in mind, we can search for accounts that haven't updated in 30 days in order to find recently aged accounts. In the first step we create a variable named $30Days
. We call Get-Date
to return the current date and time, and then use AddDays
to add a negative 30 days. This date is then stored in our variable.
We then call Get-ADComputer
to search AD for our computer accounts. We apply a filter on the lastLogonDate
attribute and search for accounts that haven't logged in for more than 30 days. We then output the computer name and when it last logged on to the domain. Once the aging accounts are identified, we can proactively find and troubleshoot the machines to ensure there is no loss of services.
In the second step we perform the same function, but this time allowing for 60 days. In this scenario, since the machines haven't logged into the domain in twice the maximum normal, we can likely assume these systems are no longer in our environment. At this point we can additionally pipe the output of this command into Disable-ADAccount
or Remove-ADComputer
to disable or delete the account in AD.
See also
More information about machine account passwords and reset policies can be found at http://blogs.technet.com/b/askds/archive/2009/02/15/test2.aspx.