Find and remove disabled AD Users with PowerShell

16. April 2015

If you have installed the “ActiveDirectory Module for Windows PowerShell” you can pretty easily handle every AD operation with PowerShell, like removing deactivated accounts for example:

Check for disabled users:

$users = Get-ADUser -Filter * | where {($_.enabled -eq $false)}

You can either measure

echo "COUNT:"
($users | measure).Count

or echo these users.

$user.UserPrincipalName

If you know want to remove those:

foreach ($user in $users)
    {
    Remove-ADUser -Identity $user.SAMAccountName
    $disabled = $user.UserPrincipalName
    "$disabled disabled."
    }

And the whole script:

$users = Get-ADUser -Filter * | where {($_.enabled -eq $false)}

echo "COUNT:"
($users | measure).Count

foreach ($user in $users)
    {
    Remove-ADUser -Identity $user.SAMAccountName
    $disabled = $user.UserPrincipalName
    "$disabled disabled."
    }

Update:
Since PowerShell 4 you can achieve this in one line:

Search-ADAccount -AccountDisabled | where {$_.ObjectClass -eq 'user'} | Remove-ADUser

PowerShell Version: 4
Modules: ActiveDirectory Module for Windows PowerShell

#PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *


*