Search code examples
powershellnested

My below Powershell script display mail contacts but does NOT display Active Directory nested distribution groups. I do not know why


I have been working 2 days to have my below Powershell script to display on the console the nested distribution groups names. But this failed and I do not know why. I do know as a matter of fact that my group named XXX has 2 mail contacts as "member" and has 2 nested distribution groups. I am just display on the console to quick verification.

I need the powershell to read the AD distribution group named "XXX" and extract and display on the console all nested distribution groups name that "XXX" group does contains as "Member Of"

Any help is more than welcome as I am running out of idea.

The script is below:

"$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://ABC.DEF.com/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session -DisableNameChecking
Import-Module Activedirectory
$groupName = 'XXX'
$groupMembers = Get-DistributionGroupMember -Identity $groupName -ResultSize Unlimited
$nestedGroups = $groupMembers | Where-Object { $_.RecipientTypeDetails -eq 'MailUniversalDistributionGroup' }
$nestedGroups | ForEach-Object { Write-Output "Nested Group: $($_.DisplayName)" }

Solution

  • As far as I know, you cannot directly retrieve nested distribution group names with the Exchange cmdlet Get-DistributionGroupMember. It can retrieve the members of a distribution group, but it does not include members from nested groups.

    A possible approach is to use Get-ADGroup from the ActiveDirectory module to retrieve AD groups, including nested groups, and then Get-ADGroupMember $myGroup -Recursive to retrieve all members of the specified group.

    # Import-Module Activedirectory
    $group = Get-ADGroup 'XXX'
    if($group){
      $nestedGroups = Get-ADGroupMember $group -Recursive | Where-Object {$_.objectClass -eq 'group'}
      $nestedGroups | ForEach-Object {Write-Output "Nested Group: $($_.Name)"}
    }
    

    4 Here's a similar discussion that shows a slightly different approach to recursively get all mailbox members of the nested groups within a specific group that might come handy.

    References:

    1. Get-ADGroup
    2. ActiveDirectory Module
    3. Get-ADGroupMember
    4. Recursively query all members within nested dynamic distribution groups of a regular distribution group