PowerShell – Removing old user accounts from your Active Directory

Earlier today I’ve posted about cleaning up your Active Directory before starting a migration by removing old computer accounts. Next would be removing old user accounts.
Normally, when a user leaves the company either the user account is removed, or disabled.

If it is removed, the issue stated earlier isn’t applicable. But when a user leaves, company policy states that the account must be kept at least 6 months and it must only be disabled.
So, only accounts that are disabled and haven’t been used for more than 6 months must be found.

To find old user accounts:
Search-ADAccount -accountdisabled | where {$_.lastlogondate -lt (get-date).addmonths(-6)} | FT Name,LastLogonDate

And to delete old user accounts:
Search-ADAccount -accountdisabled | where {$_.lastlogondate -lt (get-date).addmonths(-6)} | Remove-ADUser

Leave a Reply

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