← script library

Find and Delete Expired Active Directory User Accounts

Active DirectoryJanuary 5, 2025

In Active Directory management, keeping user accounts up to date is crucial for security and efficiency. This PowerShell script helps administrators identify and delete user accounts that have expired, enhancing directory hygiene. At ServerEngine, we provide tools to streamline your server management.

powershell
Import-Module ActiveDirectory

function Remove-ExpiredADUsers {
    $expiredUsers = Get-ADUser -Filter { AccountExpirationDate -lt (Get-Date) } -Properties AccountExpirationDate
    if ($expiredUsers) {
        foreach ($user in $expiredUsers) {
            try {
                Remove-ADUser -Identity $user SamAccountName -Confirm:$false
                Write-Host "Deleted expired user: $($user.SamAccountName)"
            } catch {
                Write-Host "ERROR: Could not delete user $($user.SamAccountName). Error: $_"
            }
        }
    } else {
        Write-Host "No expired accounts found."
    }
}

Remove-ExpiredADUsers

Run 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.

Ready when you are.

Try ServerEngine free for 7 days.