Get-DistributionGroupMember Recursive

Get-DistributionGroupMember Recursive

If you are looking to do an extract of a Distribution Group Members recursively, this article is for you.
Supposing you want to do an extract of the members of Group1, this group having direct members and nested groups as described below.

GroupsMembers
Group1User1, Group2
Group2User2, Group3
Group3User3, Group4
Group4User1, User4

Let’s try to extract its members using Get-DisributionGroupMember

Get-DistributionGroupMember -Identity Group1@jmatech.onmicrosoft.com -ResultSize Unlimited

Get-DistributionGroupMember returns only direct members of distribution group Group1 : User1 and Group2. Exchange PowerShell commands Get-DistributionGroupMember and Get-DynamicDistributionGroupMember don’t handle recursivity.

I share the below Powershell script as a solution to recursively extracts distribution group members.

function Get-GMBR{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        $Identity
    )
    Process{
        foreach ($Member in @(
                    try {
                        Get-DistributionGroupMember -Identity $Identity -ResultSize Unlimited -ErrorAction Stop
                    }
                    catch {
                        Get-DynamicDistributionGroupMember -Identity $Identity -ResultSize Unlimited
                    } 
                )
            ){
            switch ($Member) {

                {$_.RecipientType -notlike "*Group*"}{
                    $_
                }
                Default {
                    Get-GMBR -Identity $_.primarysmtpAddress
                }
            }
        }
    }
}

Let’s try to extract members of Group1 using this time the above script.

Get-GMBR -Identity Group1@domain.com

The script returns all members of Group1 taking nestings into account. However, we find that some are returned more than once. This is normal behavior if these members are also part of the nested groups. This is the case of User1 who is both a member of Group1 and Group4.

Solution : The solution is to select uniquely each member returned by our script.

$Members = Get-GMBR -Identity Group1@domain.com | Sort-Object Name | Get-Unique -AsString
$Members

To extract several group members at once

$Members = "Group1", "Group2", "GroupN" | Get-GMBR | Sort-Object Name | Get-Unique

To export result to a csv file

$Members | Select-Object DisplayName, PrimarySmtpAddress | Export-Csv -Path C:\temp\Members.csv -Encoding UTF8 -NoTypeInformation

You now have the solution.

Et voilà 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s