Created
February 17, 2025 14:37
-
-
Save chadmando/1ee6bf8200056ac8e553f66bb301df85 to your computer and use it in GitHub Desktop.
Get members of a distribution group and include nested groups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Code written by Copilot - no guarantees | |
# Function to get members of a distribution group, including nested groups | |
function Get-DistributionGroupMembers { | |
param ( | |
[string]$GroupName | |
) | |
# Get the distribution group | |
$group = Get-DistributionGroup -Identity $GroupName | |
# Initialize an array to hold all members | |
$allMembers = @() | |
# Function to recursively get members | |
function Get-Members { | |
param ( | |
[string]$GroupName | |
) | |
# Get the members of the group | |
$members = Get-DistributionGroupMember -Identity $GroupName | |
foreach ($member in $members) { | |
if ($member.RecipientType -eq 'MailUniversalDistributionGroup' -or $member.RecipientType -eq 'MailUniversalSecurityGroup') { | |
# If the member is a distribution group, call the function recursively | |
Get-Members -GroupName $member.Name | |
} else { | |
# Add the member to the array | |
$allMembers += $member | |
} | |
} | |
} | |
# Start the recursive function | |
Get-Members -GroupName $GroupName | |
# Return all members | |
return $allMembers | |
} | |
# Example usage | |
$groupName = "YourDistributionGroupName" | |
$members = Get-DistributionGroupMembers -GroupName $groupName | |
# Output the members | |
$members | ForEach-Object { Write-Output $_.Name } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment