Search code examples
powershellazure-active-directorymicrosoft365

How do I remove all licenses from a user using the AzureAD v2 Module?


I need to remove all licenses from a user in Microsoft 365 using the AzureAD v2 Powershell Module (Not MSOnline or Microsoft.Graph).

I tried following the documentation for Set-AzureADUserLicense, but it doesn't explain how to remove licenses using this cmdlet.


Solution

  • $azureUser = Get-AzureADUser -SearchString <search-string>
    
    $skuIds = New-Object -TypeName System.Collections.Generic.List[string]
    
    foreach ($license in $azureUser.AssignedLicenses)
    {
        $skuIds.Add($license.SkuId)
    }
    
    $licenses = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
    $licenses.RemoveLicenses = $skuIds
    
    Set-AzureADUserLicense -ObjectId $azureUser.ObjectId -AssignedLicenses $licenses
    

    How did I come to discover this?

    Well first we find out through the documentation (or when trying to use the cmdlet) that the AssignedLicenses parameter takes an object of type AssignedLicenses. A cursory search doesn't find any page documenting this type, but we can see a clue in the documented example. The fully qualified type is Microsoft.Open.AzureAD.Model.AssignedLicenses.

    If we instantiate an object of this type into a Powershell session, we can inspect the members. We see that there is an AddLicenses property that takes a System.Collections.Generic.List of AssignedLicense objects. This is the property used in the example explaining how to add a license.

    We also see a property called RemoveLicenses that takes a System.Collections.Generic.List of strings. We can make an educated guess that the strings need to be license SkuIds.

    Now we have everything we need to know to start testing, and we can draw some insight from the documented example of adding a license! In my answer I instantiated an AssignedLicenses object, populated it's RemoveLicenses property with a generic list of license SkuIds, passed that into the cmdlet, and voila.