Skip to content
Home » Articles » Automating M365 License Reclamation with PowerShell

Automating M365 License Reclamation with PowerShell

The Cost of Unused Microsoft 365 Licenses

In the dynamic landscape of the modern workplace, employee turnover is a constant. While offboarding procedures typically involve disabling user accounts, the crucial step of reclaiming associated Microsoft 365 licenses often gets overlooked. This oversight leads to a silent drain on IT budgets, as organizations continue to pay for licenses assigned to inactive or departed users. Beyond the financial impact, maintaining unnecessary licenses can complicate compliance audits and inflate the attack surface by retaining active entitlements for dormant accounts.

This guide provides a comprehensive, hands-on approach for Canadian businesses to automate Microsoft 365 license reclamation using PowerShell. By identifying inactive users and systematically removing their licenses, organizations can achieve significant cost savings and improve their overall security posture.

Prerequisites and Environment Checklist

Before proceeding with license reclamation, ensure your environment meets the following requirements:

  • Microsoft 365 Licensing: Applicable to all Microsoft 365 business and enterprise plans (e.g., Microsoft 365 Business Basic, Standard, Premium, E3, E5).
  • Administrative Roles:
    • Global Administrator or User Administrator for Entra ID (Azure Active Directory) to manage user accounts.
    • License Administrator or Global Administrator to manage licenses.
  • PowerShell Modules:
    • Microsoft Graph PowerShell SDK: For interacting with Entra ID and license assignments.
    • Exchange Online PowerShell Module: For checking mailbox activity.
  • PowerShell Version: PowerShell 7.x (recommended) or Windows PowerShell 5.1.

Installing Required PowerShell Modules

If you do not have the necessary modules, install them using the following commands:

# Install Microsoft Graph PowerShell SDK
Install-Module -Name Microsoft.Graph -Scope CurrentUser

# Install Exchange Online PowerShell Module
Install-Module -Name ExchangeOnlineManagement -Scope CurrentUser

Step-by-Step Implementation: Automating License Reclamation

The process involves connecting to Microsoft 365, identifying inactive users based on activity criteria, and then programmatically unassigning their licenses.

Step 1: Connect to Microsoft 365 Services

Establish secure connections to both Microsoft Graph and Exchange Online.

# Connect to Microsoft Graph with required permissions
Connect-MgGraph -Scopes "User.Read.All", "Organization.Read.All", "Directory.Read.All", "Directory.AccessAsUser.All", "LicenseAssignment.ReadWrite.All"

# Connect to Exchange Online
Connect-ExchangeOnline -ShowBanner:$false

Step 2: Define Inactivity Criteria

Determine what constitutes an “inactive” user. Common criteria include:

  • Last logon date to Entra ID.
  • Last activity date in Exchange Online (e.g., last email sent/received).
  • Account disabled status.

For this script, we will focus on Entra ID last logon and Exchange Online mailbox activity. We will set a threshold of 90 days for inactivity.

$InactivityThresholdDays = 90
$CutoffDate = (Get-Date).AddDays(-$InactivityThresholdDays)

Step 3: Identify Inactive Users

This script will fetch all licensed users and then filter them based on the defined inactivity criteria.

Function Get-InactiveLicensedUsers {
Param (
[int]$InactivityDays = 90
)

$InactiveUsers = @()
$LicensedUsers = Get-MgUser -Filter "assignedLicenses/`$count ne 0" -All | Select-Object Id, DisplayName, UserPrincipalName, LastSignInDateTime

Write-Host "Searching for users inactive for more than $InactivityDays days..."

foreach ($User in $LicensedUsers) {
$LastSignInDate = $User.LastSignInDateTime

# Check Entra ID Last SignIn Date (requires Entra ID P1/P2 for LastSignInDateTime property)
# Fallback to Exchange Online last activity if LastSignInDateTime is not available or too old
if ($LastSignInDate -and $LastSignInDate -lt (Get-Date).AddDays(-$InactivityDays)) {
    $InactiveUsers += $User
    Write-Host "Found inactive user (Entra ID): $($User.UserPrincipalName) - Last Sign-in: $($LastSignInDate)"
}
else {
    # Check Exchange Online Mailbox Activity for users not caught by Entra ID sign-in
    try {
        $MailboxActivity = Get-MailboxStatistics -Identity $User.UserPrincipalName -ErrorAction SilentlyContinue | Select-Object LastLogonTime
        if ($MailboxActivity -and $MailboxActivity.LastLogonTime -lt (Get-Date).AddDays(-$InactivityDays)) {
            $InactiveUsers += $User
            Write-Host "Found inactive user (Exchange Online): $($User.UserPrincipalName) - Last Mailbox Activity: $($MailboxActivity.LastLogonTime)"
        }
    }
    catch {
        Write-Warning "Could not retrieve mailbox statistics for $($User.UserPrincipalName): $($_.Exception.Message)"
    }
}
}
return $InactiveUsers
}

$InactiveUsersToProcess = Get-InactiveLicensedUsers -InactivityDays $InactivityThresholdDays

Step 4: Reclaim Licenses from Inactive Users

This is the critical step where licenses are removed. It is highly recommended to run this in a WhatIf mode first.

Function Remove-M365Licenses {
Param (
[Parameter(Mandatory=$true)]
[array]$Users,
[switch]$WhatIf
)

Write-Host "Attempting to reclaim licenses from $($Users.Count) inactive users."

foreach ($User in $Users) {
Write-Host "Processing user: $($User.UserPrincipalName)"
$AssignedLicenses = Get-MgUserLicenseDetail -UserId $User.Id

if ($AssignedLicenses.Count -gt 0) {
    Write-Host "  Found $($AssignedLicenses.Count) licenses for $($User.UserPrincipalName)."
    if ($WhatIf) {
        Write-Host "  WhatIf: Would remove all licenses from $($User.UserPrincipalName)."
    }
    else {
        try {
            $SkuIdsToRemove = $AssignedLicenses | Select-Object -ExpandProperty SkuId
            $RemoveLicenseParams = @{
                AddLicenses = @()
                RemoveLicenses = $SkuIdsToRemove
            }
            Set-MgUserLicense -UserId $User.Id -Body $RemoveLicenseParams
            Write-Host "  Successfully removed all licenses from $($User.UserPrincipalName)." -ForegroundColor Green
        }
        catch {
            Write-Error "  Failed to remove licenses for $($User.UserPrincipalName): $($_.Exception.Message)"
        }
    }
}
else {
    Write-Host "  No licenses found for $($User.UserPrincipalName)."
}
}
}

# --- IMPORTANT: Run in WhatIf mode first to review actions ---
Write-Host "Running in WhatIf mode. No changes will be made." -ForegroundColor Yellow
Remove-M365Licenses -Users $InactiveUsersToProcess -WhatIf

# --- Once reviewed, remove -WhatIf to perform actual license reclamation ---
# Write-Host "Running in LIVE mode. Licenses will be removed." -ForegroundColor Red
# Remove-M365Licenses -Users $InactiveUsersToProcess

Verification and Functional Testing

After running the script (without -WhatIf), verify that licenses have been successfully reclaimed.

Verification via PowerShell

# Check a specific user's license status
$UserPrincipalNameToCheck = "inactiveuser@yourdomain.com" # Replace with an actual inactive user
Get-MgUserLicenseDetail -UserId (Get-MgUser -Filter "userPrincipalName eq '$UserPrincipalNameToCheck'").Id

The output should show no assigned licenses for the specified user.

Verification via Microsoft 365 Admin Center

  1. Navigate to the Microsoft 365 admin center.
  2. Go to Users > Active users.
  3. Search for the user whose licenses were reclaimed.
  4. Click on the user, then go to the Licenses and apps tab.
  5. Confirm that all assigned licenses are unchecked or removed.

Common Troubleshooting Pitfalls and Rollback

Common Pitfalls

  • Permissions Errors: Ensure the connected user has the necessary Entra ID roles (Global Administrator, User Administrator, License Administrator).
  • LastSignInDateTime Null/Empty: This property requires Entra ID P1 or P2 licenses for the user. If not available, rely more heavily on Exchange Online mailbox activity or other identity provider logs.
  • Service Principal Licenses: The script targets user licenses. Service principal licenses (e.g., for applications) are managed differently and are not covered here.
  • Synchronization Delays: After removing licenses, it may take a short period for changes to propagate across all Microsoft 365 services.
  • Accidental Removal: Always run with -WhatIf first. If a license is accidentally removed from an active user, it must be manually reassigned via the Microsoft 365 admin center or PowerShell.

Rollback Procedure (Manual Reassignment)

If a license is mistakenly removed, it can be reassigned:

  1. Via Microsoft 365 Admin Center:
    • Go to Users > Active users.
    • Select the user, then Licenses and apps.
    • Select the required license(s) and save changes.
  2. Via PowerShell:
    • Identify the SkuId of the license to reassign. You can list available SKUs with Get-MgSubscribedSku.
    • Then, assign the license:
$UserPrincipalName = "user@yourdomain.com" # User to reassign license to
$SkuIdToAssign = "YOUR_SKU_ID" # e.g., "b055fd28-xxx-xxx-xxx-xxxxxxxx" for M365 Business Premium

$AssignLicenseParams = @{
AddLicenses = @($SkuIdToAssign)
RemoveLicenses = @()
}

Set-MgUserLicense -UserId (Get-MgUser -Filter "userPrincipalName eq '$UserPrincipalName'").Id -Body $AssignLicenseParams
Write-Host "License with SkuId $SkuIdToAssign assigned to $UserPrincipalName." -ForegroundColor Green

Need Urgent IT Assistance or Perimeter Defense?

Is your organization vulnerable to active edge exploits, credential harvesting, or compliance audit penalties? Helpdesk.ca provides 24/7/365 managed IT support, emergency incident triage, and co-managed IT escalation for Canadian enterprises.


MANAGED MODERN WORKPLACE & IT INFRASTRUCTURE

Modernize Your IT Support with Guaranteed 15-Minute SLAs

From zero-touch Intune provisioning to automated employee onboarding and proactive 24/7 endpoint management, Helpdesk.ca keeps Canadian teams productive and secure.

Sources & References

Helpdesk.ca Assistant

Please enter your details to start chatting.

Hello! How can I help you today?