Clean Up Inactive Users in Active Directory

Removing or archiving inactive users in Active Directory is important.   Cleaning up inactive users in Active Directory keeps your directory clean and organized and also can keep you safe from having old accounts hijacked. Keeping an orderly directory is part of creating a secure environment.

Clean Up Inactive Users in Active Directory with PowerShell

When you run the following script on the server, it will only fetch inactive users. You can uncomment the line “Remove-AdUser” to remove them. You could also move them to a special place you’ve reserved to archive them.

import-module activedirectory
$time = (Get-Date).Adddays(-($DaysInactive))
Get-ADUser -SearchBase "DC=vrag, DC=org" -Filter { enabled -eq $false -and
(LastLogonTimeStamp -lt $time -or -not (LastLogontimeStamp -like "*"))} -Properties LastLogonTimeStamp |
ForEach-Object {
# Removing the users just shown as an example. You could also disable them and move them in an inactive area.
# Remove-ADUser -confirm:$false -identity $_.samaccountname
Get-AdUser -identity $_.samaccountname

You’ll want to use something like Microsoft’s task scheduler to run this script unattended. You would also want to use a service account and use “-Credentials” on your PowerShell commands to keep things more secure.It’s a good idea also to send notification emails when users have been archived or removed to create a log and history if running unattended.

Web Active Directory’s PeopleAudit

Web Active Directory’s PeopleAudit allows you to do run and/or schedule these jobs without writing PowerShell.

Safely and securely specify the service account to use to perform tasks.

Configure notifications and logging to keep you aware of what’s going on.

Easily specify and configure what constitutes an inactive user.