Tuesday, 6 May 2014

Powershell Script to Disable AD User Account

Description:

In this article, I am going give powershell script examples to disable Active Directory user account by user's samAccountName and DistinguishedName, disable AD Users from specific OU, and disable Bulk AD users from CSV file using powershell script.

You can disable an ad account by using the Active Directory powershell cmdlet Disable-ADAccount.
Disable-ADAccount -Identity <adaccount>
The Disable-ADAccount cmdlet disables an Active Directory user, computer, or service account. The Identity parameter specifies the Active Directory user, computer service account, or other service account that you want to disable. You can identify an account by its distinguished name (DN), GUID, security identifier (SID), or samAccountName.

Summary:


Disable AD User Account with samAccountName

Import-Module ActiveDirectory
Disable-ADAccount -Identity MorganTest

Disable AD User Account with DistinguishedName

Import-Module ActiveDirectory
Disable-ADAccount -Identity "CN=MorganTest,OU=London,DC=TestDomain,DC=local"

Disable Active Directory Users from Specific OU

Import-Module ActiveDirectory
Get-ADUser -Filter 'Name -like "*"' `
  -SearchBase "OU=London,DC=TestDomain,DC=local" | Disable-ADAccount

Disable Bulk AD Users from CSV file using Powershell Script

   1. Consider the CSV file Users.csv which contains set of Active Directory users to disable with the attribute samAccountName.
Disable Active Directory User Account using Powershell Script

   2. Copy the below Powershell script and paste in Notepad file.
   3. Change the Users.csv file path with your own csv file path.
   4. SaveAs the Notepad file with the extension .ps1 like Disable-Bulk-AD-Users-FromCSV.ps1

Powershell script file: Download Disable-Bulk-AD-Users-FromCSV.ps1
Import-Module ActiveDirectory
Import-Csv "C:\Scripts\Users.csv" | ForEach-Object {
 $samAccountName = $_."samAccountName" 
Get-ADUser -Identity $samAccountName | Disable-ADAccount
}
   6. Now run the Disable-Bulk-AD-Users-FromCSV.ps1 file in Powershell to Disable Bulk Active Directory users from CSV file.
PS C:\Scripts>  .\Disable-Bulk-AD-Users-FromCSV.ps1
Disable Bulk AD Users From CSV File using Powershell Script

Note: I have placed script file in the location C:\Scripts, if you placed in any other location, you can navigate to that path using CD path command (like cd "C:\Downloads").


Thanks,
Morgan
Software Developer

Advertisements
Advertisements

5 comments:

  1. Many thanks Morgan !.........Works like a charm !

    ReplyDelete
  2. If I wanted to log the changes in a different file. Can that be done? Thanks in advance

    ReplyDelete
    Replies
    1. do you mean export changes once user get disabled?

      Delete
  3. this isn't working for me.. :-(

    ReplyDelete
    Replies
    1. What is the error u r receiving?

      Delete