Monday, 10 May 2021

Automatically Disable Expired Accounts in Active Directory with Powershell

Active Directory has the ability to set an expiration date on accounts so that the account becomes inactive and can't be accessed/logged into once this date has passed. The problem with the way this works, is that technically the account is still "enabled" - as it's not actually "disabled" - it's simply expired. Disabled accounts are easily identified within Active Directory Users & Computers  by a slightly different icon next to the account name. Expired accounts however, do not have any visual indication that they are expired, making them harder to identify.

I have created a powershell script which I run on a daily basis to automatically identify, and then disable any Active Directory accounts that have expired.

$report = @()
$expiredusers = get-aduser -Filter * -Properties AccountExpirationDate | where {$_.AccountExpirationDate -lt (get-date) -and $_.AccountExpirationDate -ne $null -and $_.enabled -eq $true}

if ($expiredusers)
    {
    set-aduser -identity $($user.samaccountname) -enabled $false -description $newdesc
    $report += new-object psobject -property @{Username=$($user.userprincipalname);AccountExpirationDate=$($user.accountexpirationdate);DN=$($user.distinguishedname)}
    }
The $report = @() line creates a new/blank array that we will use later on to store the results of any expired 

Next we perform a search using the get-aduser cmdlet to search all Active Directory accounts for those with an expiration date prior (less than) the current date and whose current account status is Enabled

An If statement is then run if any expired accounts are found which disables the account, and adds the account into the $report variable/array we declared earlier.

You can then export the $report variable to a CSV file, email it to yourself etc.

No comments:

Post a Comment