powershellactive-directoryactive-directory-group

List groups and number of users in AD using Powershell


I am trying to pull a list of groups from AD that start with "pegp" and a count of how many users are in each group and performing this action in PowerShell. This script will give me a list of the all the groups, but I also need how many users are in each group:

$groups = Get-ADGroup -Filter "Name -like 'pegp*'"

$Output = forEach($group in $groups) {

    Get-ADGroup -Identity $group | Select-Object name

}

$Output | Export-Csv C:\temp\file_test2.csv

I then tried this code, but it's not giving me a count of the users in each group and is actually inserting an additional row after each group name in the CSV:

$groups = Get-ADGroup -Filter "Name -like 'pegp*'"

$Output = forEach($group in $groups) {

    Get-ADGroup -Identity $group | Select-Object name
    (Get-ADGroupMember -Identity $group).count
}

$Output | Export-Csv C:\temp\file_test4.csv

Since I'm still new to PowerShell and programming in general, I thought I'd reach out to the well of knowledge to help me figure out where I'm going wrong. Thanks!


Solution

  • Your current code produces an alternating stream of 1 object with a Name property, and 1 integer, which is why Export-Csv is not producing the results you want - it's expecting uniform input.

    What you'll want to do is produce 1 object with 2 properties - for that you could use the Select-Object cmdlet with a calculated property for the member count:

    $groupsWithMemberCount = Get-ADGroup -Filter "Name -like 'pegp*'" |Select Name,@{Name='MemberCount';Expression={@(Get-ADGroupMember -Identity $_).Count }}
    
    # no need to call Get-ADGroup again, we already have all the information we need
    $groupsWithMemberCount |Export-Csv C:\temp\file_test4.csv -NoTypeInformation
    

    Beware that this counts the total number of members (principals AND nested groups).

    If you want only users, filter the ouput from Get-ADGroupMember based on their objectClass:

    $groupsWithMemberCount = Get-ADGroup -Filter "Name -like 'pegp*'" |Select Name,@{Name='MemberCount';Expression={@(Get-ADGroupMember -Identity $_ |Where-Object objectClass -eq 'user').Count}}