azurepowershellazure-active-directorymicrosoft-graph-apimicrosoft-entra-id

Powershell EntraID - Get display names of user groups


I would like to read users from an EntraID group and display their user groups in a list. So for each user of the group the respective groups should be displayed with the group name. Unfortunately, the script does not return anything in the “groups” column. Please help, I have not found anything in my research.

Connect-MgGraph -Scopes "Group.Read.All", "User.Read.All"

$groupId = ""

$groupMembers = Get-MgGroupMember -GroupId $groupId -All


$userGroups = @()

foreach ($member in $groupMembers) {
    $userId = $member.Id
    $user = Get-MgUser -UserId $userId
    $userGroupMemberships = Get-MgUserMemberOf -UserId $userId -All
    #$userGroupMemberships = $userGroupMemberships.id

    $userGroups += [PSCustomObject]@{
        UserPrincipalName = $user.UserPrincipalName
        DisplayName = $user.DisplayName
        Groups = $userGroupMemberships | ForEach-Object { 
            if ($_ -is [Microsoft.Graph.PowerShell.Models.MicrosoftGraphGroup]) {
                $_.DisplayName
            }
        }
    }
}


$userGroups | Format-Table -AutoSize

Solution

  • In both cases you can leverage the OData cast to reduce the amount of API calls. The cast essentially requests the API to only list or filter for objects of the specified type and also convert or cast said objects to the specified type, however this works on direct calls, I'm not aware if the cmdlets support it.

    The endpoints being called are:

    # simple function to handle pagination
    function page {
        param(
            [Parameter(Mandatory)]
            [string] $Uri,
    
            [Parameter()]
            [ValidateSet('HashTable', 'PSObject')]
            [string] $OutputType = 'PSObject')
    
        do {
            try {
                $req = Invoke-MgGraphRequest GET $Uri -OutputType $OutputType
                $Uri = $req.'@odata.nextLink'
                if ($req.value) {
                    $req.value
                }
            }
            catch {
                Write-Error -Exception $_.Exception
            }
        }
        while ($Uri)
    }
    
    $groupId = 'xxxx-xxx-xxxx-xxx-xxxxxx'
    $uri = "v1.0/groups/$groupId/members/microsoft.graph.user?`$select=id, displayName, userPrincipalName"
    $groupMembers = page $uri
    
    $result = foreach ($member in $groupMembers) {
        $uri = "v1.0/users/$($member.id)/memberOf/microsoft.graph.group?`$select=displayName"
        $userGroupMemberships = page $uri
    
        [PSCustomObject]@{
            UserPrincipalName = $member.UserPrincipalName
            DisplayName       = $member.DisplayName
            Groups            = $userGroupMemberships.displayName
        }
    }
    
    
    $result | Format-Table -AutoSize