Clean up in active AD accounts
Cleanup of Inactive AD Accounts (User & Computer) – Over 1 Year Old
Idea
To improve Active Directory (AD) security hygiene, performance, and compliance with ARPAN or internal IT policies by identifying and removing inactive user and computer accounts that haven’t been used for over one year.
Problem Statement
Over time, user and computer accounts in Active Directory become stale due to employee attrition, decommissioned machines, or system account redundancies. These dormant accounts pose the following risks and issues:
- Security Risks: Inactive accounts are vulnerable to misuse or compromise.
- License Wastage: Consumes unnecessary licenses in environments like Microsoft 365.
- Administrative Overhead: Clutters AD with obsolete entries, complicating management.
- Compliance Gaps: May violate policies such as ARPAN which mandate timely account lifecycle management.
Solution
Implement a PowerShell-based automated process that:
- Identifies all user and computer accounts that have not logged on in over 365 days.
- Exports these accounts to CSV files for review and audit purposes.
- Deletes the reviewed accounts safely (with optional backup and logging steps).
PowerShell Script (Summary):
Benefits
- Enhanced Security: Minimizes attack surface by eliminating dormant accounts.
- Compliance Assurance: Meets ARPAN and internal audit standards for account lifecycle.
- Operational Efficiency: Reduces clutter in AD, improving admin productivity.
- Cost Optimization: Frees up licenses and reduces overhead in systems like Office 365 or Azure AD.
Power shell script:
Load AD module
Import-Module ActiveDirectory
Set time threshold
$timeThreshold = (Get-Date).AddDays(-365)
— Export Inactive User Accounts —
$inactiveUsers = Get-ADUser -Filter {LastLogonDate -lt $timeThreshold -and Enabled -eq $true} -Properties LastLogonDate |
Select-Object Name, SamAccountName, LastLogonDate
$inactiveUsers | Export-Csv -Path “C:ADCleanupInactiveUsers.csv” -NoTypeInformation
Write-Host “Inactive users exported to InactiveUsers.csv”
— Export Inactive Computer Accounts —
$inactiveComputers = Get-ADComputer -Filter {LastLogonDate -lt $timeThreshold -and Enabled -eq $true} -Properties LastLogonDate |
Select-Object Name, SamAccountName, LastLogonDate
$inactiveComputers | Export-Csv -Path “C:ADCleanupInactiveComputers.csv” -NoTypeInformation
Write-Host “Inactive computers exported to InactiveComputers.csv”
Optional: Review before deleting
Uncomment the following lines to perform deletion
<#
Delete Inactive Users
$inactiveUsers | ForEach-Object {
Remove-ADUser -Identity $_.SamAccountName -Confirm:$false
}
Delete Inactive Computers
$inactiveComputers | ForEach-Object {
Remove-ADComputer -Identity $_.SamAccountName -Confirm:$false
}
Write-Host “Inactive users and computers deleted.”
>