TheJanitor TheJanitor - 1 year ago 162
Powershell Question

Get a count of users in a specific OU and its sub OU's

I'm looking for a

script that will get me:

  1. The name of the

  2. The count of the number of AD users in each

I have found this:

(Get-ADUser -Filter * -SearchBase “ou=Users,ou=A1,dc=contoso,dc=com”).count

This does exactly what I want, but I would have to type in each
name. The problem is that we have 100+
. The specific
I'm wanting to run this in is\cmsg\users
under the
is where the 100+

Any help would be much appreciated :).

Answer Source

A possible comprise to your issue. Each ad user contains information about its parent container. Since you are already returning all users. Lets use that to determine the counts. Caveat being that if you have user-less OU's they would not show in the results.

Get-ADUser -Filter * -Properties CN | 
    Select-Object @{Label='ParentContainer';Expression={$_.Distinguishedname -replace "CN=$($,"}} | 
    Group-Object -Property ParentContainer | 
    Select-Object Name,Count

You can of course still use -SearchBase to narrow the scope of Get-ADUser.

If this is not what you wanted your next solution would require output from Get-ADOrganizationalUnit.

$ous = Get-ADOrganizationalUnit -Filter * -SearchBase "ou=Users,ou=CMSG,dc=contoso,dc=com" | Select-Object -ExpandProperty DistinguishedName
$ous | ForEach-Object{
        OU = $_
        Count = (Get-ADUser -Filter * -SearchBase "$_").count
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download