How to clean up your Active Directory Database
It is often a mess when your server become to be old and when you do not have process for disabling/removing user from the active directory database.
I do believe it is important to decommission computer & users who are not longer logging on the domain.
So here is 2 quick PowerShell scripts which allow you to get a list of the users and computer you can disable firstly and then maybe after a certain time to be deleted.
1. Last Logon
I use this script to understand when was the last time each users were logged on.
Get-ADUser -Filter * -SearchBase “dc=<Mycompany>,dc=com” -ResultPageSize 0 -Prop CN,lastLogonTimestamp | Select CN,@{n=”lastLogonDate”;e={[datetime]::FromFileTime($_.lastLogonTimestamp)}} | Export-CSV -NoType <MyLocationToSave>
Once I filter by date I firstly disable (just to avoid some errors) then if nobody complain I will completely delete it.
2. Inactive Computers
Now for computer I query Active Directory for all computers (display Hostname & LastLogonTimestamp)
# Gets time stamps for all computers in the domain that have NOT logged in for the last year
import-module activedirectory
$domain = “<YourDomainName>”
$DaysInactive = 365
$time = (Get-Date).Adddays(-($DaysInactive))
# Get all AD computers with lastLogonTimestamp less than our time
Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties LastLogonTimeStamp |
# Output hostname and lastLogonTimestamp into CSV
select-object Name,@{Name=”Stamp”; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}} | export-csv <ExportLocation> -notypeinformation
If you are lazy or you do not like PowerShell you can use a third party tool called True Last Logon.
Download it here
That was quick but it is always useful to have a clean Active Directory. Do not hesitate to share your own tips!