Skip to content

Instantly share code, notes, and snippets.

Created October 22, 2021 09:16
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Bulk remove licenses for a list of users via the Microsoft Graph PowerShell module
Connect-MgGraph -Tenant -Scopes User.ReadWrite.All
#Import the list of users, or generate it dynamically as needed
$users = Import-Csv .\Users-to-disable.csv
#$users = Get-MgUser -Filter "Department eq 'Marketing'"
foreach ($user in $users) {
Write-Verbose "Processing licenses for user $($user.UserPrincipalName)"
try { $user = Get-MgUser -UserId $user.UserPrincipalName -ErrorAction Stop }
catch { Write-Verbose "User $($user.UserPrincipalName) not found, skipping..." ; continue }
$SKUs = @(Get-MgUserLicenseDetail -UserId $
if (!$SKUs) { Write-Verbose "No Licenses found for user $($user.UserPrincipalName), skipping..." ; continue }
foreach ($SKU in $SKUs) {
Write-Verbose "Removing license $($SKU.SkuPartNumber) from user $($user.UserPrincipalName)"
try {
Set-MgUserLicense -UserId $ -AddLicenses @() -RemoveLicenses $Sku.SkuId -ErrorAction Stop #-WhatIf
catch {
if ($_.Exception.Message -eq "User license is inherited from a group membership and it cannot be removed directly from the user.") {
Write-Verbose "License $($SKU.SkuPartNumber) is assigned via the group-based licensing feature, either remove the user from the group or unassign the group license, as needed."
else {$_ | fl * -Force; continue} #catch-all for any unhandled errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment