I suggest you come to this from a different angle. Each user of the ad contains information about their parent container. Since you are already returning all users. Let's use this to define counters. The caveat is that if you have a custom OU, they will not appear 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, use -SearchBase to narrow the scope of Get-ADUser .
If this is not what you wanted, your next solution will 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 } }
Matt
source share