Removing Old Active Directory Accounts

Find and removing old user and computer accounts from Active Directory is an important part of Active Directory maintenance. Removing unused and expired account is important in order to optimize and secure your Active Directory environment.

PowerShell is a powerful scripting environment for Windows which can be used for this type of maintenance but first you all you need to install the Active Directory Powershell tools:

1. Click Start -> All Programs -> Accessories -> Windows PowerShell -> Windows PowerShell

2. At the command prompt type:

Import-Module ActiveDirectory

3. Once the module install is complete, confirm its available by running:

Get-Module -ListAvailable | select-string -pattern "Active"

Once you have installed the Active Directory PowerShell commands you may use the following syntax to search for computers which haven’t logged in for 6 or more months:

get-adcomputer -properties lastLogonDate -filter * | where { $_.lastLogonDate -lt (get-date).addmonths(-6) } | sort Name | FT Name,LastLogonDate

To delete old computer accounts use the same syntax and pipe it through the “Remove-ADComputer” script:

get-adcomputer -properties lastLogonDate -filter * | where { $_.lastLogonDate -lt (get-date).addmonths(-6) } | Remove-ADComputer

To find Active Directory user account which haven’t logged in for 6 or more months use:

Search-ADAccount -accountdisabled | where {$_.lastlogondate -lt (get-date).addmonths(-6)} | FT Name,LastLogonDate

To delete old user accounts use the same syntax and pipe it through the “Remove-ADUser” script:

Search-ADAccount -accountdisabled | where {$_.lastlogondate -lt (get-date).addmonths(-6)} | Remove-ADUser