Make use of Extended IT to bolster your IT Support Offering
Extend your IT

Office 365 Remove Licenses from blocked users.

An MSP recently contacted me asking for a way to audit all Office 365 Licenses in use by users that have been blocked and then give them the option to remove them, this is right up my street so I immediately started work on a PowerShell script to complete this for them.

This is what I came up with:

#Blocked User Script
#Connect to MSOLOnline
$cred = Get-Credential
Write-Host "Connecting to Office 365"
Connect-MsolService -Credential $cred

$AuditMode = Read-Host -Prompt 'Do you want to run this script in audit mode (audit mode lists but doesnt remove any licenses)? (Y/N)'
$CSVPath = Read-Host -Prompt 'Please provide a full path where we can export a CSV File, leave blank for no CSV file'

$users = Get-MsolUser | Where {$_.IsLicensed -eq "True" -and $_.BlockCredential -eq "True"} | Select UserPrincipalName, Licenses

if (($users.count > 0) -or $users.UserPrincipalName -ne $null){
    Write-Host "The following users exist who are blocked and licensed"


    #Remove The Licenses
    If ($AuditMode -eq "N"){
        foreach ($user in $users){
            $upn = $user.UserPrincipalName
            (get-MsolUser -UserPrincipalName $upn).licenses.AccountSkuId |
                    Set-MsolUserLicense -UserPrincipalName $upn -RemoveLicenses $_
            Get-MsolUSer -UserPrincipalName $upn | Select UserPrincipalName, Licenses

    #Export the Licenses
    If ($CSVPath -ne $null){

        foreach ($user in $users){
        $MSOLLicenses = ""
        foreach($MSOLLic in $user.Licenses){
            $MSOLLicenses = $MSOLLicenses + $MSOLLic.AccountSkuId
        $upn = $user.UserPrincipalName

        $table="$UPN, $MSOLLicenses"
        $table | Out-File $CSVPath -Encoding Ascii -Append 



} else {

   Write-Host "There are no Licensed users who are blocked, exiting script..."

Get-PSSession | Remove-PSSession

It requires the MS Online PowerShell module but that’s it. It will prompt you to run in Audit or Live mode and outputs any changes to a CSV file.

To get the live version of this script go here –¬†https://github.com/ExtendedIT/PowerShell/tree/master/Remove-LicenseBlockedUser

For any help on this script or other Powershell issues drop me an email – [email protected]