Try the following (ensure you have the Active Directory module for PowerShell installed)
# Define the path to save the CSV file
$outputFile = "C:\ExportedUsers.csv"
# Get all groups by filtering for security groups, mail-enabled security groups, and distribution groups
$groups = Get-ADGroup -Filter {GroupCategory -eq 'Security' -or GroupCategory -eq 'Distribution'}
# Initialize an empty array to store results
$results = @()
# Iterate over each group
foreach ($group in $groups) {
# Get all members of the group, including those in nested groups
$members = Get-ADGroupMember -Identity $group -Recursive | Where-Object { $_.objectClass -eq 'user' }
# Add each member's details to the results array
foreach ($member in $members) {
$results += [pscustomobject]@{
GroupName = $group.Name
UserName = $member.SamAccountName
UserDisplayName = $member.Name
UserEmail = $member.EmailAddress
}
}
}
# Export results to a CSV file
$results | Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8
Write-Output "Export completed: $outputFile"
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin