Script to list The Members of Nested Distribution Groups

Connect to Exchange Online PowerShell

$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session

Get list of all distribution groups

$groups = Get-DistributionGroup -ResultSize unlimited

Loop through each group and get its members

foreach ($group in $groups) {
Write-Host “Group: $($group.Name)”
$members = Get-DistributionGroupMember -Identity $group.Name -ResultSize unlimited
foreach ($member in $members) {
Write-Host “Member: $($member.Name)”
}
}

Disconnect from Exchange Online PowerShell

Remove-PSSession $Session

Summary

This script first connects to Exchange Online PowerShell using the New-PSSession cmdlet and your Office 365 credentials. It then uses the Get-DistributionGroup cmdlet to get a list of all distribution groups in your organization.

For each group, the script uses the Get-DistributionGroupMember cmdlet to get a list of its members, including members of any nested distribution groups. It then loops through each member and writes their name to the console.

Finally, the script disconnects from Exchange Online PowerShell using the Remove-PSSession cmdlet.

Note that this script assumes that you are using Exchange Online PowerShell to manage your Office 365 distribution groups. If you are using an on-premises Exchange Server, you may need to modify the script to use the appropriate cmdlets and connection settings.

———————————————————————————————————————————–

Following is another way of doing this as I noticed some people had issues with the above script. I did test the following and it worked fine so far.

Load the Active Directory module

Import-Module ActiveDirectory

Function to recursively get members of a group, including nested groups

function Get-NestedGroupMembers($GroupName) {
$group = Get-ADGroup $GroupName
$members = Get-ADGroupMember $group | Where-Object { $_.objectClass -eq ‘user’ }

# Recursively process nested groups
$nestedGroups = Get-ADGroupMember $group | Where-Object { $_.objectClass -eq 'group' }
foreach ($nestedGroup in $nestedGroups) {
    $members += Get-NestedGroupMembers $nestedGroup
}

return $members

}

Get a list of all distribution groups in Active Directory

$allDistributionGroups = Get-ADGroup -Filter {GroupCategory -eq ‘Distribution’}

Iterate through each distribution group and get its members, including nested groups

foreach ($group in $allDistributionGroups) {
$groupName = $group.Name
$members = Get-NestedGroupMembers $groupName

# Output the group name and its members
Write-Host "Group: $groupName"
foreach ($member in $members) {
    Write-Host "  Member: $($member.Name)"
}

}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑