Using the AD Powershell cmdlets to find inactive accounts

By | June 23, 2012

For a number of years now I have been using OldCmp  to find and remove inactive user and computer accounts.  The other day I thought I would have a crack at using the AD Powershell cmdlets to at least do the finding part.  It wasn’t as difficult as I thought.  Here’s an example looking for enabled accounts that have been inactive for 90 days or more:

# Find inactive user accounts

$now = Get-Date
$old = $now.AddDays(-90)
Get-ADUser -Filter * -Properties lastlogondate `
| ? {($_.enabled -eq $true) -and ($_.lastlogondate -le $old)} `
| select samaccountname, lastlogondate `
| Export-Csv .\inactive_users.csv -NoTypeInformation

# Find inactive computer accounts

$now = Get-Date
$old = $now.AddDays(-90)
Get-ADComputer -Filter * -Properties lastlogondate `
| ? {($_.enabled -eq $true) -and ($_.lastlogondate -le $old)} `
| select name, lastlogondate `
| Export-Csv .\inactive_computers.csv -NoTypeInformation

I normally use LDAP filters for all searches, but in this case I used a standard Powershell filter.  Why? Well, because the cmdlets expose two pseudo attributes: “enabled” and “lastlogondate”.  I call these pseudo attributes because you won’t find them anywhere in the AD schema.  They are provided to make life easier.   The alternative would be to query userAccountControl with a bitwise filter  to find the enabled/disabled state and to do some formatting with lastLogonTimestamp, which is stored in AD as a large integer value.

I hope you find these useful.

One thought on “Using the AD Powershell cmdlets to find inactive accounts

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.