Disable AD User based on specific attribute using Powershell

In this article, I am going write powershell script to disable Active Directory user account by using user’s specific property like employeeNumber, employeeID, etc…You can disable an ad user account by using the Active Directory powershell cmdlet Disable-ADAccount.

Disable-ADAccount -Identity <adaccount>

The Identity parameter specifies the Active Directory user that you want to disable. You can identify an account by its distinguished name (DN), GUID, security identifier (SID), or samAccountName.

Using the above command, you can not find user by using other AD attributes. So, we need to use another cmdlet Get-ADUser to find user using specific attribute and then we can pipe the result to Disable-ADAccount command to disable.

The following command search an AD user by user’s EmployeeID using SQL like filter and disable the user.

Import-Module ActiveDirectory
Get-ADUser -Filter 'employeeID -like "1200547"' | Disable-ADAccount

You can also find an user by using well-known LDAP Filter. The following command find user by LDAP filter using user’s EmployeeID and disable the user.

Import-Module ActiveDirectory
Get-ADUser -LDAPFilter '(employeeID=1200547)'  | Disable-ADAccount

Disable Bulk AD Users from CSV by User’s EmployeeID

The following powershell script import AD users from csv file and disable by using user’s EmployeeID property. Consider the CSV file Users.csv which contains set of AD users to disable with the attribute EmployeeID as one of the csv column header.

Import-Module ActiveDirectory
Import-Csv "C:\Users.csv" | ForEach-Object {
$employeeID = $_."EmployeeID"
Get-ADUser -LDAPFilter "(employeeID=$employeeID)"  | Disable-ADAccount
Write-Host "User $employeeID disabled"
}

Advertisement

Leave a Comment