#PSTip Disabling multiple AD user accounts

Note: This tip requires PowerShell 2.0 or above.

The Disable-ADAccount cmdlet disables an Active Directory user, computer, or service account. When you need to disable multiple accounts you might find yourself trying something obvious like:

PS> Disable-ADAccount -Identity user1,user2,user3

But that doesn’t work and yields an error. The Identity parameter doesn’t accept multiple values.  The typical solution is to use the services of the ForEach-Object cmdlet and pass one account at a time:

echo user1 user2 user3 | ForEach-Object {
   Disable-ADAccount -Identity $_

Fortunately there’s a better and easy way to do that by simply piping the values directly to Disable-ADAccount. By default, Disable-ADAccount does not generate any output. Add the -PassThru switch if you want to see the modified object(s).

echo user1 user2 user3 | Disable-ADAccount -PassThru
Filed in: Columns, Tips and Tricks Tags: , ,

10 Responses to "#PSTip Disabling multiple AD user accounts"

  1. Agha says:

    What if your trying to disable multiple users from a list in a text file?

    • PowerShellMag says:

      No problem, assuming each name appears on a line of its own, read and pipe the content to the Disable-ADAccount cmdlet:

      Get-Content users.txt | Disable-ADAccount -PassThru

    • ShayLevy says:

      Another thing you can do:

      Get-ADUser -Filter {telephoneNumber -eq ‘3011234’} | Disable-ADAccount

  2. matt says:

    This is great but what if i want to search based on telephone number (our staff ID numbers are stored in that field) and the boss often asks ‘disabe 3011234’ for example

  3. Gregory says:

    My company has 2 sites and each site has been sold to different organizations and we are breaking the network connectivity between the 2 sites. Once the network is split we will be seizing FSMO and cleaning up AD. Is there a way in powershell to disable all users in a specific OU and all sub-OUs?

  4. Shay Levy says:

    @Gregory, sure you can. Remove the -WhatIf switch to apply the operation :

    Get-ADUser -Filter * -SearchBase ‘OU=Users,OU=MySite,DC=domain,DC=com’ -SearchScope Subtree | Disable-ADAccount -WhatIf

  5. Shay Levy says:

    @Matt, you can use the Filter parameter, see the help of the parameter for usage examples.
    Once the filter is applied you can pipe the result to the Disable-ADAccount cmdlet.

  6. Gregory says:

    Sweet, Thanks!

  7. Eydie says:

    I have a script that disables account in bulk perfectly, however I need to add to that script. I need it to email me a list of names that were disabled. What would that script look like?

Leave a Reply

Submit Comment

© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: