Unlicense Disabled Office 365 Users

We have a constant churn of staff, as does any large organisation. One of the challenges is to ensure that anyone who has left has their account disabled in AD. All good, we have that process. We also use Azure AD Sync to sync users to our Office 365 tenant.

Disabling a user however, does not remove the licence assigned them, so I decided to create a simple PowerShell script that I can run periodically to find all the blocked users in Office365 and remove any licences they had.

This script requires PowerShell 5..

#clear the screen
CLS
#Lets log the output.. Remeber to change this to a location you want!
Start-Transcript -path C:\temp\output.txt -append
#Connect To your tenant..
Connect-MsolService 
#get a list of all users who's sign in status is blocked..
Write-Output "getting Blocked users..."
$users = Get-MsolUser -All | Where-Object {$_.BlockCredential -eq "True"} | Select -Property UserPrincipalName
Write-Output "Starting unlicense module.."
#remove licences from these users..
foreach ($user in $users)
 { 
 #ok, lets see what license they have..
 $license = Get-MsolUser -UserPrincipalName $user.UserPrincipalName | Select-Object -ExpandProperty Licenses
 #make sure you change this to your country!
 Set-MsolUser -UserPrincipalname $user.UserPrincipalName -UsageLocation "GB"
 #go ahead and remove the licence
 if ($license.AccountSkuId -ne $null)
 {
 Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -RemoveLicense $license.AccountSkuId
 #lets log what we did so we can report on it. Managers love reports..
 
 Write-Output $user.UserPrincipalName removed $license.AccountSkuId 
 }

 }
 Write-Output "Finished"
 Stop-Transcript

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.