Search code examples
powershellazure-active-directoryoffice365

Find out the direct assigned licenses of an o365 user


I am trying to write a powershell script, where I need to remove the licenses of the user. However, I only need to remove the license if it is assigned directly and not via some Azure group. I do not have to touch the licenses which are showing up because of group based policy.

While testing, I noted that for the licenses property of a msoluser there also exists GroupsAssingningLicense which I could explore, however it contains value even for direct assign licenses.

Is there way I can figure out if the license is a direct assign or is showing up due to user being part of some group?


Solution

  • Your direction is correct.

    We really should filter according to GroupsAssingningLicense.

    For a direct assigned license, the value of GroupsAssingningLicense is the object id of the user.

    But for an inherited assigned license, the value of GroupsAssingningLicense is the object id of the group.

    A sample for your reference:

    Connect-MsolService
    
    $username = ""
    
    $user = Get-MsolUser -UserPrincipalName $username
    
    foreach ($license in $user.Licenses){
        if($license.GroupsAssigningLicense[0].ToString() -eq $user.ObjectId){
            Write-Host $license.AccountSkuId
            Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -RemoveLicenses $license.AccountSkuId
        }
    }