I get multiple requests from customers where they want accounts to be deactivated after not being logged in for X number of months. Some also want to delete the accounts when disabled for another X number of months.
For now I have created a script which disables accounts in specific folders after 90 days not being used and deletes them after being disabled for 6 months.
Note that the scripts checks if the customers CanonicalName contains the OU “NamedAccounts” as I place customer accounts in there so service accounts or my own account does not get locked.
## Disable account if not used for X days $90Days = (get-date).adddays(-90) $users = Get-ADUser -properties * -filter {((lastlogondate -notlike "" -OR lastlogondate -le $90Days) -AND (enabled -eq $True))} | where CanonicalName -Like "NamedAccounts*" | select-object SAMaccountname foreach ($user in $users) { write-host Disabling account $user.SAMaccountname Disable-ADAccount -Identity $user.SAMaccountname } ## Delete account if disabled for X months. $6Months = (get-date).AddMonths(-6) $users = Get-ADUser -properties * -filter {((modifyTimeStamp -le $6Months) -AND (enabled -eq $False))} | where CanonicalName -Like "NamedAccounts" | select-object SAMaccountname foreach ($user in $users) { write-host Deleting account $user.SAMaccountname Remove-ADUser -Identity $user.SAMaccountname }
Just save this script to a powershell script and schedule it using task scheduler to run it daily.