TheJanitor TheJanitor - 4 months ago 28
Powershell Question

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

I'm looking for a

powershell
script that will get me:


  1. The name of the
    OU's

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



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
OU
name. The problem is that we have 100+
OU's
. The specific
OU
I'm wanting to run this in is
contoso.com\cmsg\users
under the
cmsg\users
is where the 100+
OU's
reside.

Any help would be much appreciated :).

Answer

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=$($_.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{
    [psobject][ordered]@{
        OU = $_
        Count = (Get-ADUser -Filter * -SearchBase "$_").count
    }
}