Get-ADGroupMembers of all groups, separate and count them by object class.


I am part way through the report I am trying to build, but the Powershell is not strong in this one. :frowning: I have been able to pull a list of all AD groups, and then do a recursive count on the objects within said group which includes all nested groups. The format I get in a text file as two columns (the group’s name and the object count). I would like to get more specific on this by having my output be Group Name, Total Object Count, User Count, Computer Count, and Nested Group Count. I presume I need to use the objectclass option for each of these subcomponents and then store that data as a variable for each of the desired counts and then put that into the file, but I am not sure of the format I should use.

Any help would be greatly appreciated.

Thank you.

This script will pull a list of AD groups from the specified OU and then report on the number of objects in each group.

$desiredOU = “OU=Groups,OU=toplevel,DC=local,DC=com”
$data = @()
Get-ADGroup -SearchBase $desiredOU -Filter {Name -like “*”} |
foreach {
$data += New-Object -TypeName PSObject -Property @{
Name = $.Name
MemberCount = (Get-ADGroupMember -Identity $($
.DistinguishedName) -recursive | Measure-Object ).Count
$data >c:\groups.txt

You want to leverage the Power of Powershell by returning a PSObject.

$desiredOU = "OU=Groups,OU=toplevel,DC=local,DC=com"

$grpMembers = foreach ($group in (Get-ADGroup -SearchBase $desiredOU -Filter *)) {
    Get-ADGroupMember -Identity $($group.DistinguishedName) -recursive | 
    Select Name, 

Now we have an object containing all of the group membership stored in the $grpMembers variable. Try running the following next:

$grpMembers | Group-Object -Property Group | Sort-Object -Property Count -Descending 

If you notice, in addition to your count and name, you have a Group property that has separated all of the AD groups into “sub-groups”. I don’t know what you want to actually do with all of the counts, but you can do further analysis several ways. You can use calculated expressions to do queries against the sub-groups:

$grpMembers | 
Group-Object -Property Group | 
Sort-Object -Property Count -Descending |
Select Name,
       @{Name="UserCount";Expression={@($_.Group | Where{$_.ObjectClass -eq 'User'}).Count}},
       @{Name="ComputerCount";Expression={@($_.Group | Where{$_.ObjectClass -eq 'Computer'}).Count}}

I would also recommend that you do a search from Powershell AD Group Report and you’ll probably find some complete solutions. The tough part is usually showing all of the nesting, so I wouldn’t re-invent the wheel if there is solution built to do what you’re looking for.