Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 680
TheJanitor Avatar asked Sep 09 '15 15:09

TheJanitor


3 Answers

I like this one - outputs exactly what original poster was after:

$root_ou = "ou=Users,ou=cmsg,dc=contoso,dc=com"
$User = get-aduser -filter * -SearchBase $ou -SearchScope Subtree | Select @{Name="OU";Expression={$_.distinguishedName -match "cn=.*?,OU=(?<OU>.*)" | Out-Null;$Matches.OU}}
$User | Group -Property OU | Select Name,Count

Output looks like this

Name                                                       Count
----                                                       -----
Office 1,ou=Users,ou=cmsg,dc=contoso,dc=com                1230
Office 2,ou=Users,ou=cmsg,dc=contoso,dc=com                390
Office 3,ou=Users,ou=cmsg,dc=contoso,dc=com                90
Office 4,ou=Users,ou=cmsg,dc=contoso,dc=com                10

To find the DistinguishedName of the root_ou you're after:

Get-ADOrganizationalUnit -Filter 'Name -like "*"' | Format-Table Name, DistinguishedName -A 
like image 136
Eric Nord Avatar answered Oct 25 '22 01:10

Eric Nord


Here is the PowerShell command to Get a count of users in a specific OU.

(Get-ADObject -Filter * -SearchBase "path of your OU").Count
like image 28
Yahkoob Ayappally Avatar answered Oct 25 '22 02:10

Yahkoob Ayappally


I propose you come at this from another angle. 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
    }
}
like image 21
Matt Avatar answered Oct 25 '22 02:10

Matt