Delete expired accounts in Active Directory



In an facebook user group another user asked how to use powershell to delete expired user accounts. He wanted to use excel to store expiration date and username etc etc. Since AD have accountexpirationdate property built in, it is better to use the AD as content database instead of excel. I answers with this simple script and since the reply got the thumbs up i think it solved his problem.

$days_date = Get-Date
$users = get-aduser -Filter 'AccountExpirationDate -LT $days_date'

foreach ($usr in $users)
{Remove-ADUser $usr

This is just a simple core to remove users, you could expand the script to for example use a quarantine lets say you want to use a quarantine for 60 days, I would create a quarantine OU and instead of deleting users that has expired “today” i would move them to that OU. After that you could create a new  get-date string but with the add_days method you could remove 60 days so you only remove user accounts older then 60 days:

$date = (get-date).AddDays(-60)

You could also build a log. To do that you could begin with an empty hash table in front of the foreach-loop and then use the name property from the $usr and $get-date do get the date when it was removed, after that you have to use the GetEnumerator method when you export to CSV, it could look something like this:

$date = get-date
$log = @{}
foreach ($usr in $users)
$log.GetEnumerator() | select name, value | export-csv -NoTypeInformation C:\test\log.csv