Skip to content

Instantly share code, notes, and snippets.

@michevnew
Created October 21, 2021 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michevnew/d289e11ee503f9baa713ab7f3ce06fc6 to your computer and use it in GitHub Desktop.
Save michevnew/d289e11ee503f9baa713ab7f3ce06fc6 to your computer and use it in GitHub Desktop.
Bulk remove licenses for a list of users via the Azure AD PowerShell module
$users = Import-Csv .\Users-to-disable.csv
foreach ($user in $users) {
Write-Verbose "Processing licenses for user $($user.UserPrincipalName)"
try { $user = Get-AzureADUser -ObjectId $user.UserPrincipalName -ErrorAction Stop }
catch { continue }
$SKUs = @($user.AssignedLicenses)
if (!$SKUs) { Write-Verbose "No Licenses found for user $($user.UserPrincipalName), skipping..." ; continue }
$userLicenses = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
foreach ($SKU in $SKUs) {
$userLicenses.RemoveLicenses += $SKU.SkuId
}
Write-Verbose "Removing license(s) $($userLicenses.RemoveLicenses -join ",") from user $($user.UserPrincipalName)"
try {
Set-AzureADUserLicense -ObjectId $user.ObjectId -AssignedLicenses $userLicenses -ErrorAction Stop
}
catch {
if ($_.Exception.ErrorContent.Message.Value -eq "User license is inherited from a group membership and it cannot be removed directly from the user.") {
Write-Verbose "At least one of the user's licenses is assigned via group-based licensing feature, use the Azure AD blade to remove it"
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