Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bulk remove licenses for a list of users via the Microsoft Graph PowerShell module
Connect-MgGraph -Tenant tenant.onmicrosoft.com -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 $user.id)
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 $user.id -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."
continue
}
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