Assign licenses with the Microsoft Graph PowerShell SDK

How to assign Office/Microsoft 365 licenses using Graph PowerShell module (Microsoft Graph PowerShell SDK)?

With the discontinuation of the Azure AD PowerShell module, Office 365 customers may be forced to update many existing scripts:

Migrate your apps to access the license managements APIs from Microsoft Graph – Microsoft Tech Community

The specific date mentioned here is June 30, 2022. After this date, there will be no more security updates. A simple example is a license script which all customers need, that cannot make use of group-based licensing. Dies könnte zum Beispiel der Fall sein, wenn keine Azure AD Premium P1 Lizenzen verfügbar sind oder eigene automatisierte Bestellprozesse etabliert sind, welche die Nutzung dieser Funktion unmöglich machen.

I recently had exactly this case in a project – and I didn’t want to manually assign the license to several hundred users. So I used the Microsoft Graph PowerShell SDK. The resulting short script can serve as a template for standardized license assignments. Before commissioning in your own company, the following may have to be adapted (the corresponding lines are highlighted):

  • The assigned license type is Exchange Online Plan 1. Replace this in line 2 with the correct license required.
  • All users who are members of the users-o365 group will be licensed. Replace this name with any other matching group in line 6. This group must be available in Azure AD.

The complete script:

Connect-Graph -Scopes User.ReadWrite.All, Organization.Read.All,Directory.ReadWrite.All
$ExOPlan1 = Get-MgSubscribedSku | where SkuPartnumber -eq "EXCHANGESTANDARD"

#Set UsageLocation for all users that have none
Get-MgUser -All | where { $_.UsageLocation -eq $null -and $_.UserType -eq 'Member' }  | %{Update-MgUser -UserId $_.UserPrincipalName -UsageLocation "DE" }
$licgroup = Get-MgGroup -Filter "Displayname eq 'users-o365'"

Get-MgGroupMember -GroupId $licgroup.Id -All| %{((Get-MgUser -UserId $_.Id).UserPrincipalName); Set-MgUserLicense -UserId ((Get-MgUser -UserId $_.Id).UserPrincipalName) -AddLicenses @{SkuId = $ExOPlan1.SkuId} -RemoveLicenses @()} 

Code language: PowerShell (powershell)

The most challenging part of the above script development was to find out which ID is needed as parameter. The Graph PowerShell SDK often (in contrast to the conventional Windows PowerShell) does not need the name of an object to be searched, but ID, objectID or similar.

The finished script is of course available for download on GitHub.

Published by Andreas

Founder of M365 Evangelists Cloud-Architect, Strategy Consultant, Consultant for Microsoft technologies, Graph API enthusiast, PowerShell enthusiast