Forum Discussion
Reclaiming licenses from deleted users
I have experienced this issue as well. Our de-provisioning process now includes removing the licenses, however some still slip through. So, I found a way to fix the issue:
All of this part is done in PowerShell while connected and logged in to the MSOLService
1. Run the command Get-MsolUser –ReturnDeletedUsers | select UserPrincipalName,IsLicensed | export-csv <Some file path where you want the file>
2. Open the file in Excel, sort by IsLicensed and delete any that are False. Save the file
3. Paste the following script in to a text editor:
Import-Csv <The file you created above> | foreach{
$UPN = $_.UserPrincipalName
Restore-MsolUser -UserPrincipalName $UPN
(get-MsolUser -UserPrincipalName $UPN).licenses.AccountSkuId |
foreach{
$License = $_
echo "Removing license: $License"
Set-MsolUserLicense -UserPrincipalName $UPN -RemoveLicenses $License
}
Remove-MsolUser -UserPrincipalName $UPN -Force
}
4. Save the script after you updated it with the file name. Make sure you end the file name with .ps1
5. Run the script in PowerShell.
The script reactivates the account, removes any license assigned to the account and then removes the account. You can run the command Get-MsolUser –ReturnDeletedUsers again afterwards to ensure all accounts now show False under IsLicensed.
Thanks a lot !
finally, after spending 2 full days on searching for a simple and short script for bulk removal of all directly assigned to users licenses, I found this brilliant !
made some cosmetic changes, and wish to put 2 scripts here for others who may have same challenge
#Connects to your Office365 tenant
Connect-MsolService
# ============================================
# remove licences from deleted users
$delUsers = Get-MsolUser -ReturnDeletedUsers | Where-Object {$_.IsLicensed -eq $true}
$delUsers | foreach {
$UPN = $_.UserPrincipalName
Restore-MsolUser -UserPrincipalName $UPN
(get-MsolUser -UserPrincipalName $UPN).licenses.AccountSkuId | foreach {
$License = $_
echo $UPN, "Removing direct license: $License"
Set-MsolUserLicense -UserPrincipalName $UPN -RemoveLicenses $License -ErrorAction SilentlyContinue
}
Remove-MsolUser -UserPrincipalName $UPN -Force
}
# ==============================================
# remove all directly assigned licences from all *domain.com users (when you use Azure AD group targeted licensing)
$Users = Get-MsolUser -All | Where-Object {$_.IsLicensed -eq $true -and $_.UserPrincipalName -like '*domain.com'}
$Users | foreach {
$UPN = $_.UserPrincipalName
(get-MsolUser -UserPrincipalName $UPN).licenses.AccountSkuId | foreach {
$License = $_
echo $UPN, "Removing direct license: $License"
Set-MsolUserLicense -UserPrincipalName $UPN -RemoveLicenses $License -ErrorAction SilentlyContinue
}
}