Forum Discussion
Eivind_G
Sep 09, 2022Copper Contributor
Get AzADGroupMembers from nested groups
Hi,
I'm trying to get all members of a group (including nested groups members) to add to a teams private channel.
We have a script to add members of a group to a private channel, but it will not add nested groups members.
$members = Get-AzADGroupMember -ObjectId 'source_groupID_here' | select mail
$tal = 0
foreach ($member in $members)
{
$User = $member.mail
Add-TeamChannelUser -GroupId 'teams_groupID_here' -DisplayName 'Private_channel_name' -user $User
$tal += 1
}
$tal
Is there a way to add those who are members of the nested groups without having to add each nested group individually?
- ChrisBradshawIron Contributor
Eivind_G here's a suggestion. Get-AzADGroupMember doesn't have a -recurse parameter like it's on-premises Active Directory equivalent, but you can recursively search through the groups with something like this:
function Get-AzADGroupMemberNested($ObjectId) { #Get the members of this group $members = Get-AzADGroupMember -ObjectId $ObjectID foreach ($member in $members) { if ($member.OdataType -eq "#microsoft.graph.group") { #If member is a group then recursively look at group membership Get-AzADGroupMemberNested -ObjectId $member.ID } elseif ($member.OdataType -eq "#microsoft.graph.user") { #If member is a user Add to Team Channel #Get mail of User associated with ID $User = (Get-AzADUser -objectid $member.ID).mail Add-TeamChannelUser -GroupId 'teams_groupID_here' -DisplayName 'Private_channel_name' -user $User } } } Get-AzADGroupMemberNested -ObjectId 'source_groupID_here'
- Hob987Copper Contributor
ChrisBradshaw This is a modified version I use to get members on nested groups:
function Get-AllGroupMembers { param ( [Parameter(Mandatory = $true)] $GroupId ) # force results into array in case of one member $members = @(Get-AzADGroupMember -ObjectId $GroupId) foreach ($member in $members) { if ($member.OdataType -eq "#microsoft.graph.group") { # If the member is a subgroup, recursively get its members $subgroupMembers = Get-AllGroupMembers $member.Id $members += $subgroupMembers } } return $members } Get-AllGroupMembers $group.id
Worth to take a look at this:
How to get AzureAD Group Members nested groups in PowerShell (baswijdenes.com)