Automate Active Directory User Cleanup by Last Logon Date
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. Visit [ServerEngine](https://serverengine.co) to discover more tools designed for efficiency.
### Step 1: Import the Active Directory Module
Ensure that you have the Active Directory module available in your PowerShell session. This module contains all necessary cmdlets to manage Active Directory users.
“`powershell
Import-Module ActiveDirectory
### Step 2: Define the Function to Clean Up Inactive Accounts
We will create a function named `Remove-InactiveADUsers` that identifies user accounts that havent been logged into for a specified number of days and proceeds to remove them.
“`powershell
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: $_" } } }
### Step 3: Execute the Cleanup Function
Now, execute the function to perform the cleanup. You can specify how many days define an inactive account.
“`powershell
Remove-InactiveADUsers -DaysInactive 90
### Conclusion
This PowerShell script allows you to automate the cleanup of inactive user accounts in Active Directory, helping improve your organizations security posture. For more tools that enhance your IT management capabilities, check out [ServerEngine](https://serverengine.co).