Search code examples
powershell

Get count of members of an active directory group?


Is it possible to get a count of members that belong to a specific group based on the OU? When I run the code below it is giving me the value of 3 for each OU when there is only 1 OU that has a value of 3, the rest should be 0. It is running the Get-ADGroupMember -Identity “Test_Group”).count against the whole active directory structure instead of just for each OU??

import-module activedirectory
foreach ($ou in  Get-ADOrganizationalUnit  -filter * -SearchScope 1){

 $computers = 0 + (get-adcomputer -filter * -searchbase $ou.distinguishedname).count    


 $ou | add-member -membertype noteproperty -name Computers -value $computers -force 


 Foreach ($Member in  $ou){

 (Get-ADGroupMember -Identity “Test_Group”).count 

 }

 $ou | select name,computers 

}

Solution

  • My interpetation of your question is that for a paricular AD Group you are looking for a member count based on OU or container.

    Get-ADGroupMember -Identity "insert_your_group" -Recursive | 
            Where-Object{$_.objectClass -eq "User"} |
            Get-ADUser -Properties canonicalname | 
            Select-Object @{Name='Container';Expression={$_.canonicalname | split-path -parent}} |
            Group-Object container |
            Select Name,Count
    

    Breaking this down line by line

    1. Grab all member of a particular group as well including members of other groups.
    2. Ensure we are only processing users and not the group themselves. We already have all the users from the -Recursive so the groups themselves can be ignored.
    3. Get all the user objects with a Get-ADUser call. We need the canonicalname as that is how we get the information for the parent container
    4. Here is the fun part. Using the canonicalname split it up (like you would a directory) and just take the -parent portion.
    5. Group the objects in order to get the count you are looking for. You can use -NoElement if the users themselves is not used in a downstream process.
    6. Simplify output with a select-object statment.

    Output

    Name                                                                    Count
    ----                                                                    -----
    Domain.Local\OU\SubOU                                                   8
    Domain.Local\OU\SubOU2                                                  8
    Domain.Local\OU\SubOU5                                                  2