Find and Delete Expired Active Directory User Accounts

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. Explore our software solutions at [ServerEngine](https://serverengine.co).
### Step 1: Import the Active Directory Module
Ensure that the Active Directory module is imported. This module contains the necessary cmdlets for managing users in AD.
“`powershell

Import-Module ActiveDirectory

### Step 2: Define the Function to Find Expired Users
Well create a function named `Remove-ExpiredADUsers` that checks for user accounts that are expired and deletes them.
“`powershell

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."
    }
}

### Step 3: Execute the Function
Now, run the function without any parameters to initiate the deletion of expired user accounts.
“`powershell

Remove-ExpiredADUsers

### Conclusion
This script serves as a reliable way to manage expired Active Directory user accounts, thereby improving the security posture of your organization. For more tools and resources to enhance server management, be sure to check out [ServerEngine](https://serverengine.co).