Search-ADAccount :: Finding Inactive, Disabled or Expired Accounts

The Search-ADAccount cmdlet has switches -AccountDisabled, -AccountExpired and -AccountInactive; the results of which may not be mutually exclusive nor inclusive.

i.e. an account which was disabled yesterday but has only been inactive for 1 week may not show up as disabled if our timespan is -90 days. Conversely an account which has not yet been disabled but hasn't been used in a while would show up as inactive but not disabled.

Is there a way to use these switches to list all disabled, expired OR inactive accounts; or do I have to run three queries then do a | select * -unique to remove duplicates?


Solution 1:

Here's how I'd do it.

Get-ADUser -Filter * -Properties Enabled, AccountExpirationDate, LastLogonDate | ? { `
($_.Enabled -EQ $False) -OR `
($_.AccountExpirationDate -NE $NULL -AND $_.AccountExpirationDate -LT (Get-Date)) -OR `
($_.LastLogonDate -NE $NULL -AND $_.LastLogonDate -LT (Get-Date).AddDays(-90)) }

One call to AD, gets only the properties that we need. Includes all users who are either disabled, or expired (an uncommon setting,) or "inactive."

Notice that LastLogonDate will be null if the user account was created but the user never logged on.

The AccountExpirationDate will also be null most of the time, as administrators do not often use that setting. You need to check that they are not null before meaningful comparisons against dates can be done against them.

If you wanted to include user accounts that never logged on, simply remove the check for $Null on LastLogonDate... but that means you will see accounts that may have been created yesterday and just haven't had the chance to log in yet... in which case, to compensate, add a check for WhenCreated -LT (Get-Date).AddDays(-90) to be sure to only get accounts that were created over 90 days ago but never logged on.

And to actually answer your question concerning the Search-ADAccount cmdlet... no, use a different cmdlet, those switches are mutually exclusive.