List all users from AD Groups with membership details
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,}', "|" }