Active Directory Powershell get [the count of] all enabled users in a certain OU [but not in sub OU’s]

For our internal use, I devised a powershell command that lists all enabled users in a certain OU, butĀ filtering out those in sub OU’s.

Unfortunately this is not a dynamic process, since it is based on the currentĀ implementation of OU’s, meaning the humans laid their hands on it. So depending on your setup you may need to exclude some sub OU’s that you don’t want to count.

First I want to list all users, then only in a certain OU to find that I want only enabled users, oh and leave out those in sub-OU’s. Oh and only the count please. Okay.


(Get-ADUser -LDAPFilter "(&(sAMAccountName=*)(!userAccountControl:1.2.840.113556.1.4.803:=2))" -SearchBase 'OU=Users,OU=Customer,DC=WindowsDomain,DC=DomainExtension' | Where-Object { $_.DistinguishedName -notmatch 'Service Accounts|OtherAccounts'}).Count

(I think .Count doesn’t count to 1 (coz then it’s not an array), be aware of that)

Hope this helps you.


This entry was posted in Active Directory, powershell. Bookmark the permalink.