In short: this script finds Active Directory user accounts that nobody has logged into for 90 days, saves them to a CSV report, and only disables them when you add the -Disable switch.
Hello and welcome back! Every AD I have worked on has the same problem: leavers who were never disabled, test accounts from a project three years ago, and service accounts nobody remembers creating. Every one of them is an account an attacker can use, and auditors love to ask about them.
Clicking through Active Directory Users and Computers to find them takes forever, so here is the script I use. It has two safety features: by default it only reports, and it supports -WhatIf so you can see exactly what it would do before it does it.
The script
#Requires -Modules ActiveDirectory
[CmdletBinding(SupportsShouldProcess)]
param(
[int]$DaysInactive = 90,
[string]$SearchBase = (Get-ADDomain).DistinguishedName,
[string]$DisabledOU, # optional: move disabled accounts here
[string]$ReportPath = "C:\Temp\StaleAccounts_$(Get-Date -Format yyyyMMdd).csv",
[switch]$Disable # without this switch the script only reports
)
$ErrorActionPreference = 'Stop' # if anything fails (e.g. the report can't be saved), stop before disabling
$cutoff = (Get-Date).AddDays(-$DaysInactive)
$stale = Search-ADAccount -AccountInactive -TimeSpan "$DaysInactive.00:00:00" -UsersOnly -SearchBase $SearchBase |
Where-Object { $_.Enabled } |
Get-ADUser -Properties LastLogonDate, WhenCreated, Description |
Where-Object { $_.WhenCreated -lt $cutoff } # skip brand new accounts that never logged on yet
# -WhatIf:$false = always write the report, even in -WhatIf mode
$stale | Select-Object Name, SamAccountName, LastLogonDate, WhenCreated, Description, DistinguishedName |
Export-Csv -Path $ReportPath -NoTypeInformation -WhatIf:$false
Write-Host "$($stale.Count) stale account(s) found. Report: $ReportPath"
if ($Disable) {
foreach ($user in $stale) {
$note = "Disabled by stale-account script $(Get-Date -Format yyyy-MM-dd) - last logon $($user.LastLogonDate)"
if ($user.Description) { $note += " | was: $($user.Description)" } # keep the old description
Disable-ADAccount -Identity $user
Set-ADUser -Identity $user -Description $note
if ($DisabledOU) {
Move-ADObject -Identity $user.DistinguishedName -TargetPath $DisabledOU
}
}
}
How to use it
Save it as Get-StaleAccounts.ps1 and run it from a machine that has RSAT (the ActiveDirectory module) installed.
- Report only (changes nothing):
.\Get-StaleAccounts.ps1 - See what it would do:
.\Get-StaleAccounts.ps1 -Disable -WhatIf - Do it for real, only in one OU, and move the accounts to a “Disabled Users” OU:
.\Get-StaleAccounts.ps1 -SearchBase "OU=Staff,DC=contoso,DC=com" -DisabledOU "OU=Disabled Users,DC=contoso,DC=com" -Disable
Quick explanation
Search-ADAccount -AccountInactivefinds users whose last logon is older than the number of days you give it.- It skips accounts that are already disabled, and accounts created in the last 90 days, so a new starter who has not logged in yet is not caught.
- Every account found goes into the CSV first, so you have a record to send to HR or your manager. The CSV is written even with
-WhatIf, and if it can’t be saved the script stops before disabling anything. - When it disables an account it writes the date and last logon into the Description field and keeps the old description after it, so the next admin knows why it was disabled and what it was for.
A couple of gotchas
- LastLogonDate can be up to about 14 days behind. It comes from the
lastLogonTimestampattribute, which only replicates every 9–14 days by default. That is fine for a 90-day check, but do not use this for a 7-day one. - Exclude service accounts. Some service accounts never log on interactively. Point
-SearchBaseat your user OUs rather than the whole domain, or keep service accounts in their own OU. - Disable, don’t delete. Leave disabled accounts for 30 days or so before deleting them. Turning an account back on is easy; restoring a deleted one is not.
You can also run this as a scheduled task every month and email the CSV to yourself. More on that in a later post. Hope this helps!
