Powershell - check if all users in a specific OU are disabled, disable if not

6,043

Solution 1

Something like this:

Get-ADUser -Filter * -SearchBase "ou=TheOU,dc=contoso,dc=com" | Disable-ADAccount

You might need to upgrade your Powershell version if it doesn't have the commands.


Try/Catch example:

$users = Get-ADUser -Filter * -SearchBase "ou=TheOU,dc=contoso,dc=com"    

ForEach ($user in $users) {
    Try {
        Disable-Account
    }
    Catch {
        Write-Output "$($user) is already disabled."
    }
    Finally {
        # Cleanup tasks, etc.
    }
}

Solution 2

To avoid disabling disabled accounts you can filter them out:

Get-ADUser -Filter {Enabled -eq $true} -SearchBase "ou=TheOU,dc=contoso,dc=com" `
| Disable-ADAccount
Share:
6,043

Related videos on Youtube

Npv23g
Author by

Npv23g

:0XXk' .. o0x. ckd' 'oO0000xxxO00xl,. .. :NMMX: .. .xWK. 'XMNd .,XMWd.. ..dNMWK,.. 'XXWMWO' .. dWK. .'.. . .KMWo. ;XMMX. ;Xd,OWMXc ... oWK. .. .. .KMWo. .KMMX. .. . :Nx .lXMM0; . .oW0. .:ldOOc. .:lxOOc;lx0XO; .KMWo. :NMX: .cdk0KKkc. . ,lkO0000x. cNO .kWMNo. .lNO .;NMWd. .:NMW0c;;OWNd. .KMWo....;dXXo. ,0Nx,. ,0MWO. kWWo. .oX, lW0. cXMMK: cNk .NMWd. .NMNl. .'. .KMWo,ldl::. ;XWO'....dNMX. .KMW0l.. ,... oWK. .dWMWd.;Xx. .NMWd. .NMNl. .KMWo. 0MWKdllc::::, ,kXWMWW0d,. . oWK. ;0MMXkNo .NMWd .NMNl .KMWo. 0MMK' . ..;o0WMWO. oWK. .oNMMNc .NMWo .NMNl .KMWo ,XMMKc.. .. 'xKo ;XMX. .xWK ,OWNl .XMNo .XMNc .KMWo 'xXWMWKOkxdd; .kNWOlco0Kk, ... ... .... ... .... ..',,... ..,;,..

Updated on September 18, 2022

Comments

  • Npv23g
    Npv23g almost 2 years

    I tried to search for it but I didn't find anything. Could someone help me out with an example of a script that would do this?

    • Vasili Syrakis
      Vasili Syrakis about 10 years
      As far as I know you can't lock them, but you can disable them.
    • Npv23g
      Npv23g about 10 years
      @VasiliSyrakis i meant disable..
  • software is fun
    software is fun over 9 years
    the script disables every account and DOES check to see which accounts are disabled