Script to bulk remove a specific license from specific users

AB123 351 Reputation points

Hi all,

I have using: ## Bulk Remove licenses ## ## Select Csv file $csv = Get-ChildItem -Path C:\temp\Office365Licence\Remove\ -File | Out-GridView -PassThru ## Import Csv $users = Import-Csv $csv.FullName ## Select Account SKU to be removed $accountSKU  = Get-MsolAccountSku | Select-Object AccountSkuId | Out-GridView -PassThru ## Loop through each user in the Csv foreach($user in $users){ Write-Host "Removing $($accountSKU.AccountSkuId) licence from $($user.UserPrincipalName)" -ForegroundColor Yellow ## Remove licence Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -RemoveLicenses $accountSKU.AccountSkuId }

Which removes license off bulk users however only does like 5 before it exceeds limit, i have read somewhere I need to usee the MSgraph to do this but what would the script be?

Microsoft 365
Microsoft 365
Formerly Office 365, is a line of subscription services offered by Microsoft which adds to and includes the Microsoft Office product line.
3,699 questions
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,008 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 43,916 Reputation points
    Hello there,
    Check with the below script
    # Install the Microsoft 365 PowerShell module if you haven't already
    # Install-Module -Name PowerShellGet -Force -AllowClobber
    # Install-Module -Name MSOnline -Force -AllowClobber
    # Connect to Microsoft 365 using PowerShell
    # Define the specific license you want to remove
    $licenseToRemove = "ENTER_LICENSE_SKU_NAME_HERE"
    # Define a list of user UPNs (User Principal Names) you want to remove the license from
    $usersToRemoveLicenseFrom = @(
    # Loop through each user and remove the specific license
    foreach ($user in $usersToRemoveLicenseFrom) {
        try {
            $userDetails = Get-MsolUser -UserPrincipalName $user
            # Check if the user has the specified license
            if ($userDetails.Licenses | Where-Object { $_.AccountSkuId -eq $licenseToRemove }) {
                Write-Host "Removing license $($licenseToRemove) from $($userDetails.UserPrincipalName)..."
                Set-MsolUserLicense -UserPrincipalName $user -RemoveLicenses $licenseToRemove
                Write-Host "License removed successfully."
            } else {
                Write-Host "User $($userDetails.UserPrincipalName) does not have the specified license."
        } catch {
            Write-Host "Error removing license for $($user): $($_.Exception.Message)"
    # Disconnect from Microsoft 365
    Hope this resolves your Query !!
    --If the reply is helpful, please Upvote and Accept it as an answer–
    0 comments No comments