Group count can be a useful piece of data, I use it sometimes to check the consistency of a group between on-premises and Azure Active Directory.

This sample issues two graph queries:

  1. Get the group object using a filter
  2. Get the group members and the member count

A bonus in this sample is the use of a VM to get the Azure AD access token. I like this because:

  • it requires no user interaction
  • it requires no secrets, passwords or certificates

For more information about getting a token using the VM identity: Azure Instance Metadata Service

# Get an access token using the VM identity
$AzureInstanceMetadataServiceUrl = '' 
    $token = Invoke-RestMethod -Uri "$AzureInstanceMetadataServiceUrl&resource=" -Headers @{Metadata=$true} -Verbose:$false
    throw "Failed to get AAD access token : $_"

# Get the group using a filter
$groupUrl = "`$filter=mailnickname eq 'PedalPushers'"
$groupResult = Invoke-RestMethod -Headers @{Authorization = "Bearer $($token.access_token)"} -Uri $groupUrl -Method Get

# Get the group member count using the group ID
$groupMemberCountUrl = "$($`$count=true&`$top=1"
$groupMemberCountResult = Invoke-RestMethod -Headers @{Authorization = "Bearer $($token.access_token)";ConsistencyLevel = 'Eventual'} -Uri $groupMemberCountUrl -Method Get