0

Is there a Microsoft Graph API to find out the number of users in an AAD group? Currently, here is my code on how I find it out. Curious to know if there is a quicker way?

            private async Task<int> GetUserIds(string groupId)
            {
                List<string> userIds = new List<string>();

                var usersFromGroup = await _groupMembersService.GetGroupMembersPageByIdAsync(groupId);
                usersFromGroup.AdditionalData.TryGetValue("@odata.nextLink", out object nextLink);
                var nextPageUrl = (nextLink == null) ? string.Empty : nextLink.ToString();
                userIds.AddRange(usersFromGroup.OfType<Microsoft.Graph.User>().Select(x => x.Id));

                while (!string.IsNullOrEmpty(nextPageUrl))
                {
                    usersFromGroup = await _groupMembersService.GetGroupMembersNextPageAsnyc(usersFromGroup, nextPageUrl);
                    usersFromGroup.AdditionalData.TryGetValue("@odata.nextLink", out object nextLink2);
                    nextPageUrl = (nextLink2 == null) ? string.Empty : nextLink2.ToString();
                    userIds.AddRange(usersFromGroup.OfType<Microsoft.Graph.User>().Select(x => x.Id));
                }

                return userIds.Count;
            }
        }

        public async Task<IGroupTransitiveMembersCollectionWithReferencesPage>GetGroupMembersPageByIdAsync(string groupId)
        {
            return await this.graphServiceClient
                                    .Groups[groupId]
                                    .TransitiveMembers
                                    .Request()
                                    .Top(this.MaxResultCount)
                                    .WithMaxRetry(this.MaxRetry)
                                    .GetAsync();
        }

        public async Task<IGroupTransitiveMembersCollectionWithReferencesPage> GetGroupMembersNextPageAsnyc(
            IGroupTransitiveMembersCollectionWithReferencesPage groupMembersRef,
            string nextPageUrl)
        {
            groupMembersRef.InitializeNextPageRequest(this.graphServiceClient, nextPageUrl);
            return await groupMembersRef
                .NextPageRequest
                .GetAsync();
        }
user989988
  • 3,006
  • 7
  • 44
  • 91

1 Answers1

0

You can use this graph API to get the count for any Group. https://graph.microsoft.com/v1.0/groups/{group-object-id}/members/$count

Make sure to add the ConsistencyLevel = Eventual in request headers for this. Tested this in Graph Explorer for you :

MS Graph Explorer Screenshot

Mario Varchmin
  • 3,704
  • 4
  • 18
  • 33