Disable inactive AD accounts

I realized many test AD accounts were going unchecked in my AD environment and decided to delete the ones which have not been used in last 90 days. I created following scripts to complete this task.

Using this single line powershell command you can find all such accounts which needs deletion.

Get-ADUser -SearchBase "DC=Domain,DC=net" -Filter {samaccountname -like "*test*"} -properties * | ? { $_.enabled -like "true" -and $_lastlogontimestamp -lt (get-date).AddDays(-90) } | select samaccountname,enabled,whencreated,@{n="lastlogontimestamp";e={([datetime]::FromFileTime($_.LastLogonTimeStamp))}} | Export-Csv C:\temp\StaleTestUsers.csv -NoTypeInformation

Using below script these accounts can be disabled and moved to another OU.

$testusers = Get-ADUser -SearchBase "DC=Domain,DC=net" -Filter {samaccountname -like "*test*"} -properties * | ? { $_.enabled -like "true" }
foreach ($testuser in $testusers){
if($_.lastlogontimestamp -lt (get-date).AddDays(-90)){
Disable-ADAccount -Identity $testuser
Move-ADObject -Identity $testuser -TargetPath "OU=DisabledAccounts,DC=Domain,DC=net"
}
}

1 Comment

Leave a Reply

Your email address will not be published.


*