From PowerShell to Azure AD License Assignment

Starting a new Azure AD tenant today, it is easy to take in Azure AD License Assignment, perhaps even using dynamic groups to automate license assignment for different Roles in your organization.

But before we had License Assignment in Azure AD, the method of choice was a PowerShell Script running in a Schedule Task. This is then equal to using the web interface and assign licenses to users one by one. So they all get status Direct-licensed, compared to group-licensed.

Fairenough, doesn’t seem to be of any challenge, until you wanne change to Group-based license assignment using Azure AD License Assignment.

Because, when you apply group-based, they will keep direct-licenses as well. So if you take away any sub-license with group-based, they will continue to have a license, because of the direct license.

So we need a way to clean up the mess of direct-licenses, and continue on with only group-based licensing.

Here is a script to find all users with a direct assigned license, and have the direct licenses removed: Just be sure your users are assigned the group-based license, before your remove the direct assigned license, else they will have a time frame without any license.

# Catch all users with a license assigned.
$Users = Get-MsolUser -All | Where-Object {$_.isLicensed}

# Catch all users with a direct assignment (and assigned license by a group in order not to remove users with only direct license assigned):
$DirectLicensedUsers = $Users | Get-UserLicenseSource | Where-Object {$_.AssignedDirectly -and $_.AssignedFromGroup)}

# Convert to a hashtable to reduce executing time
$LicenseHash = $DirectLicensedUsers | Group-Object -Property UserPrincipalName -AsHashTable

Foreach ($user in $LicenseHash.Keys)
{
    $SkusToRemove = $LicenseHash[$User].SkuID
    Set-MsolUserLicense -UserPrincipalName $User -RemoveLicenses $SkusToRemove
}
This seemed to be the most common scenario out there, despite Microsoft own scripts not taking in this consideration.

Leave a Reply

Ehlo!

I am Roy Apalnes, a Microsoft Cloud Evangelist working av Sopra Steria. Main focus in Microsoft Security and Endpoint Management, with a bigger picture in mind.

Featured Posts