Licences per office location using MS Graph

Hello all

I’m struggling to get my head round so I’m hoping someone is willing to give me a shove in the right direction.

My users in M365 have their “Office” field set with a 3,4 or 5 letter code. I want to list the number of M365 licences of each type per office.

I can write to the console with the following but how do I do the count? Should I create a two dimensional array or should I be using nested loops somehow?

foreach ($MgUser in $MgUsers) {Write-Host $MgUser.UserPrincipalName ", " $MgUser.OfficeLocation ; Get-MgUserLicenseDetail -UserId $MgUser.UserPrincipalName -Property SkuPartNumber}

Thanks in advance.

Hi, welcome to the forum :wave:

You could create a custom object, and use Group-Object:

$MgUserList = Get-MgUser

$LicenceData = foreach ($MgUser in $MgUserList) {
    $SkuPartNumber  = Get-MgUserLicenseDetail -UserId $MgUser.UserPrincipalName -Property SkuPartNumber | 
        Select-Object -ExpandProperty SkuPartNumber

    [PSCustomObject]  @{
        UserPrincipalName = $MgUser.UserPrincipalName
        OfficeLocation    = $MgUser.OfficeLocation
        SkuPartNumber     = $SkuPartNumber        
    }
}

$LicenceData | Group-Object OfficeLocation,SkuPartNumber | Select-Object Name,Count
2 Likes

@matt-bloomfield - stunning! Thank you.

It does almost exactly what I needed and after reading through the code quickly I ran it and it worked.

I will swot up on the PSCustomObject and Group-Object as they seem to be the key and what I didn’t know about. Thank you very much for the pointer.

Reckon’ I’ll hang around here some more.

1 Like