I have a bunch of groups whose membership count I need as part of some code I am writing. So far I had a loop like this:
1 2 3 4 |
$licensedViaGroupsCount = 0 foreach ($group in $licensingGroupsArray) { $licensedViaGroupsCount += (Get-MgGroupMember -GroupId $group.Id -All).Count } |
This does the job but is slow. Then I remembered reading somewhere about the $count
parameter – in fact, here in the official docs. A screenshot:
And it works for groups too, great. Digging into the groups documentation, I find an example in this page too.
That sounds straight forward then. The Get-MgGroupMember
has a -Count
parameter but I couldn’t get that working. I tried the following for instance, expecting to have a variable called blahblah
with the count… but got nothing!
1 |
Get-MgGroupMember -GroupId 24fc3f5c-5653-4258-82ab-bdf15996fb13 -CountVariable blahblah |
No worries, lets try Invoke-MgGraphRequest instead.
1 |
Invoke-MgGraphRequest 'https://graph.microsoft.com/v1.0/groups/24fc3f5c-5653-4258-82ab-bdf15996fb13/members/$count' -Method 'GET' -Headers @{ ConsistencyLevel = 'eventual' } |
Nope, nothing! Without ConsistencyLevel: eventual
it errors, so pass it in the headers definitely makes a difference. (I noticed this header in the docs above, that’s why I passed it).
Curious about ConsistencyLevel I Googled and came across this interesting blog post. That’s a good read, and has an example of just what I want (the 3rd one below)!
So does that work? Nope!
1 |
Invoke-MgGraphRequest 'https://graph.microsoft.com/v1.0/groups/24fc3f5c-5653-4258-82ab-bdf15996fb13/transitiveMembers/$count' -Method 'GET' -Headers @{ ConsistencyLevel = 'eventual' } |
What the heck! (I tried the beta Url too, not just v1.0 as above)
The same query works fine when using Graph Explorer… so it seems to be an Invoke-MgGraphRequest
issue.
Luckily I then stumbled upon this Reddit post where someone asked the same question and got an answer just 12 days ago (good timing for me!). Here’s what they did:
1 2 3 4 5 6 7 8 9 |
$tempFile = [System.IO.Path]::GetTempFileName() $uri = 'https://graph.microsoft.com/v1.0/groups/{insert group id here}/transitiveMembers/$count' Invoke-MgGraphRequest -Method GET -Uri $uri -Headers @{ConsistencyLevel = "eventual" } -ContentType "text/plain" -OutputFilePath $tempFile Get-Content -Raw $tempFile Remove-Item $tempFile |
Apparently it’s a bug and the above workaround of saving it to a file instead is the workaround. Nice! I also learnt of [System.IO.Path]::GetTempFileName()
in the process… wasn’t aware of that! (So far I’d just create a file with some random numbers in the TEMP
location when I wanted a temporary file).