← script library

Automated User Account Cleanup

Users & AccountsDecember 27, 2024

This PowerShell script automates the process of cleaning up inactive user accounts in Active Directory. It is especially useful for organizations looking to maintain security and good management practices. By utilizing this script, administrators can efficiently identify and remove accounts that have been inactive for a specified duration. This is particularly important when using software like ServerEngine, as it helps ensure that only active users have access to resources, thus enhancing security.

powershell
param (
    [int]$inactiveDays = 90
)
# Calculate the date of inactivity threshold
$thresholdDate = (Get-Date).AddDays(-$inactiveDays)
# Get all user accounts from Active Directory
Import-Module ActiveDirectory
$inactiveUsers = Get-ADUser -Filter {LastLogonDate -lt $thresholdDate} -Properties LastLogonDate
foreach ($user in $inactiveUsers) {
    # Remove each inactive user account
    Remove-ADUser -Identity $user -Confirm:$false
    Write-Output "Removed inactive user: $($user.SamAccountName)"
}
Write-Output "User account cleanup completed. Inactive accounts older than $inactiveDays days have been removed."

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.