Created
October 21, 2021 08:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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