Posted in : Azure, Microsoft

3 years ago

When working with on-premise Active Directory an administrator often has to recursively search AD groups, this is easy using the ActiveDirectory module with cmdlet ”Get-AdGroupMember <Group> -Recusive”.
For the AzureAD equivalent this is no longer an option, the cmdlet Get-AzureADGroupMember has three parameters.
-All <Boolean>
If true, return all group members. If false, return the number of objects specified by the Top parameter
-ObjectId <String>
Specifies the ID of a group in Azure AD.
-Top <Int32>
Specifies the maximum number of records to return.

As we can see there is no -recursive, in order to search recursively I’ve written the function below.

Function Get-RecursiveAzureAdGroupMemberUsers{
    Process {
        Write-Verbose -Message "Enumerating $($AzureGroup.DisplayName)"
        $Members = Get-AzureADGroupMember -ObjectId $AzureGroup.ObjectId -All $true
        $UserMembers = $Members | Where-Object{$_.ObjectType -eq 'User'}
        If($Members | Where-Object{$_.ObjectType -eq 'Group'}){
            $UserMembers += $Members | Where-Object{$_.ObjectType -eq 'Group'} | ForEach-Object{ Get-RecursiveAzureAdGroupMemberUsers -AzureGroup $_}
    end {
        Return $UserMembers

The function accepts groups by parameter or by pipeline and returns only the object type ’User’
To run a recursive AzureAD Group member search simply pipe a normal ADgroup search as below

Get-AzureADGroup -SearchString 'AzureADGroupName' | Get-RecursiveAzureAdGroupMemberUsers

Tags : Azure, AzureAD, Get-AzureAdGroupMember, PowerShell, Recusive


Jay Antoney says

There is a problem with this. If the group you are searching contains another GROUP before a MEMBER then the script never creates the $UserMembers array and therefore fails with the error.
> Method invocation failed because [Microsoft.Open.AzureAD.Model.User] does not contain a method named 'op_Addition'.

Vikingur Saemundsson says

Hi, I can't see the scenario where this would be a problem. Perhaps if we find a group without any usermembers? Are you inputing an object with both groups & users into the function?
Does it help to encapsulate everything into try/catch clauses?
Try{$UserMembers = $Members | Where-Object{$_.ObjectType -eq 'User'}}
Catch{$UserMembers = @()}
If($Members | Where-Object{$_.ObjectType -eq 'Group'}){
$UserMembers += $Members | Where-Object{$_.ObjectType -eq 'Group'} | ForEach-Object{ Get-RecursiveAzureAdGroupMemberUsers -AzureGroup $_}

Add comment

Your comment will be revised by the site if needed.