powershellactive-directory

Get-ADGroup member count domain issue


I'm rather new to Powershell. I need to gather a list of certain Groups and the member count of these and the nested groups. I first used Get-ADGroupMember.

$groupsWithMemberCount = Get-ADGroup -Filter "Name -like 'GROUP*'" |Select Name,@{Name='MemberCount';Expression={@(Get-ADGroupMember -Identity $_ -Recursive).Count }}
$groupsWithMemberCount | out-gridview #Export-Csv C:\temp\file_test4.csv

That did not work since one of the nested groups is an external group which I cannot access. After that I used Get-ADGroup.

$groupsWithMemberCount = Get-ADGroup -Filter "Name -like 'GROUP*'" |Select Name,@{Name='MemberCount';Expression={@(Get-ADGroup $_ -Properties *).Member.Count }}
$groupsWithMemberCount | out-gridview #Export-Csv C:\temp\file_test4.csv

Which does now show me all the nested groups but doesn't count the members in those nested groups. I tried using -SearchScope Subtree but it does not seem to work.

$groupsWithMemberCount = Get-ADGroup -Filter "Name -like 'GROUP*'" |Select Name,@{Name='MemberCount';Expression={@(Get-ADGroup $_ -SearchScope Subtree -Properties *).Member.Count }}
$groupsWithMemberCount | out-gridview #Export-Csv C:\temp\file_test4.csv

What could I change so I get a "simple" list of Group names and the member count of those and the nested groups?


Solution

  • What you're looking to count is objects that are a memberOf each group so you can do:

    $sb = { @(Get-ADObject -LDAPFilter "(memberOf=$($_.DistinguishedName))" ).Count }
    
    $groupsWithMemberCount = Get-ADGroup -Filter "Name -like 'GROUP*'" |
        Select-Object Name, @{ Name = 'MemberCount'; Expression = $sb }
    

    And if you want to do recursive members of the groups you can do:

    $sb = { @(Get-ADObject -LDAPFilter "(memberOf:1.2.840.113556.1.4.1941:=$($_.DistinguishedName))" ).Count }
    
    $groupsWithMemberCount = Get-ADGroup -Filter "Name -like 'GROUP*'" |
        Select-Object Name, @{ Name = 'MemberCount'; Expression = $sb }
    

    Note that this method will only bring counts of members in the Domain. It doesn't query members from external Domains.