List all users from AD Groups with membership details

Created by Jeremy Burgess, Modified on Fri, 30 Jun, 2023 at 4:48 PM by Jeremy Burgess

Symptoms

You want to quickly list all users in Active Directory groups.

Cause

n/a

Resolution

The script below takes a list of group names and will parse each. Users will be listed and sub-groups will also be parsed. This is very useful for documenting all members in a nested group situation such as FileDirector users.


The resulting output is pipe delimited so can be copied into a spreadsheet and easily converted to table format.

$groupNames = @(
    "fd-admins",
    "fd-scan",
    "fd-scan-named",
    "fd-user",
    "fd-user-named"
)

$users = @{}

function Get-GroupMembers {
    param (
        [Parameter(Mandatory = $true)]
        [string]$GroupName
    )

    $group = Get-ADGroup -Filter "Name -eq '$GroupName'"
    if ($group) {
        $members = Get-ADGroupMember -Identity $group.DistinguishedName | Where-Object { $_.objectClass -eq "user" }
        if ($members) {
            foreach ($member in $members) {
                $user = Get-ADUser -Identity $member.DistinguishedName -Properties SamAccountName, Name
                $username = $user.SamAccountName

                if ($users.ContainsKey($username)) {
                    $users[$username] += ", " + $group.Name
                } else {
                    $users[$username] = $group.Name
                }
            }
        } else {
            Write-Output "No members found in the group '$GroupName'."
        }

        $subGroups = Get-ADGroup -Filter {MemberOf -RecursiveMatch $group.DistinguishedName}
        if ($subGroups) {
            foreach ($subGroup in $subGroups) {
                Get-GroupMembers -GroupName $subGroup.Name
            }
        }
    } else {
        Write-Output "Group '$GroupName' not found."
    }
}

Get-GroupMembers -GroupName $groupName

# Display the summarized table
$users.GetEnumerator() | Sort-Object @{Expression={$_.Key}; Ascending=$true} | Select-Object @{Name='Username'; Expression={$_.Key}}, @{Name='ContainingGroups'; Expression={$_.Value}} | Format-Table -AutoSize | Out-String -Stream | ForEach-Object { $_ -replace '\s{2,}', "|" } 

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article