Azure ARM Group Membership Recursively – Part 1
I recently ran into a scenario where we needed to get all members of an Azure ARM group recursively. I wanted to use connect-msolservices, which I read about in Johan Dahlbom’s post regarding recursively enumerating Azure AD Group members with PowerShell. The problem I ran into was using this inside of Azure Automation with service principal names. The solution was to convert it over to AzureRmAD command.
Examples
Let’s say you found a group and now you want to get the members or sub group members or sub sub group members. Awesome sauce.
First get the object id of the group.
[code language=”powershell”] Get-AzureRmADGroup -SearchString topgroup1 [/code]
———– —- ——–
topgroup1 Group 32d312f1-bb16-43cb-be24-e4f1b03dcf6b
If you want just the current user members, simply run:
[code language=”powershell”]  Get-RecursiveGroupMembers -ObjectId ’32d312f1-bb16-43cb-be24-e4f1b03dcf6b’ [/code]
DisplayName Type ObjectId
———– —- ——–
admin User 22cc957a-15d0-41c5-b338-e24d682c9209
If you want all top level members and all recursive members, run:
[code language=”powershell”]  Get-RecursiveGroupMembers -ObjectId 32d312f1-bb16-43cb-be24-e4f1b03dcf6b’ -Recursive[/code]
DisplayName Type ObjectId
———– —- ——–
admin User 22cc957a-15d0-41c5-b338-e24d682c9209
mbamrw User e05b2529-3aa7-43f9-9e15-ea7ea8b2cc97
Here is the function that you can copy and paste into PowerShell. Once you run this, you will be able to use Get-RecursiveGroupMembers:
[code language=”powershell”]
function Get-RecursiveGroupMembers {
param(
[CmdletBinding(SupportsShouldProcess=$true)]
[Parameter(Mandatory=$true, ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
[ValidateScript({Get-AzureRmADGroup -ObjectId $_})]$ObjectId,
[parameter(Mandatory=$false)]
[switch]
$Recursive
)
$topMembers = Get-AzureRmADGroupMember -GroupObjectId $ObjectId | where {$_.type -eq ‘user’}
if ($topMembers) {$toplist += $topmembers}
$UserMembers = @()
if ($PSBoundParameters[‘Recursive’]) {
$GroupsMembers = Get-AzureRmADGroupMember -GroupObjectId $ObjectId| where {$_.type -eq ‘group’}
if ($GroupsMembers) {
$GroupsMembers | ForEach-Object -Process {
$UserMembers += Get-RecursiveGroupMembers -Recursive -ObjectId $_.id -Verbose
}
$sublist += $UserMembers
}
}
$userlist = (($sublist + $toplist) | sort-object -Property userprincipalname -Unique)
return $userlist
}
[/code]
In my next post I will show you how to pull all members of a Resource Group Recursively using this function. I’ll also show how to pull the inherited members if there are no admins assigned. Stay tuned.