← script library
Automate Active Directory User Cleanup by Last Logon Date
Active DirectoryJanuary 5, 2025
Managing user accounts effectively in Active Directory is crucial for security and operational efficiency. This PowerShell script helps administrators identify and remove user accounts that have not been logged into for an extended period. Automating this cleanup process can help maintain a secure and organized Active Directory environment. At ServerEngine, we provide innovative solutions to streamline your IT tasks.
powershell
Import-Module ActiveDirectory
function Remove-InactiveADUsers {
param (
[int]$DaysInactive = 90
)
$timeThreshold = (Get-Date).AddDays(-$DaysInactive)
$inactiveUsers = Get-ADUser -Filter { LastLogonDate -lt $timeThreshold } -Properties LastLogonDate
foreach ($user in $inactiveUsers) {
try {
Remove-ADUser -Identity $user.SamAccountName -Confirm:$false
Write-Host "Deleted inactive user: $($user.SamAccountName)"
} catch {
Write-Host "ERROR: Could not delete user: $($user.SamAccountName). Error: $_"
}
}
}
Remove-InactiveADUsers -DaysInactive 90Run it across your fleet
This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.
More in Active Directory
Active Directory User Onboarding with PowerShell
2026-08-17Active Directory User Offboarding with PowerShell
2026-08-17Disable an Active Directory User with PowerShell
2026-08-17Enable an Active Directory User with PowerShell
2026-08-17Unlock an Active Directory Account with PowerShell
2026-08-17Reset an Active Directory Password with PowerShell
2026-08-17Ready when you are.
Try ServerEngine free for 7 days.