2017-01-12

Had a look around internet and couldn’t find anywhere a script to add/remove Office 365 licenses in bulk using PowerShell.  There were a lot of examples about how to set these fresh (without consideration for what is already set), so quickly conjured this up…. Someone may find it helpful.

A quick note on the scenario – The company I am working at had already disabled some licenses for some users.  I was asked to disable PowerApp and Flow.  Now I couldn’t simply set the license options as follows.

$accountID = (Get-solAccountSku).AccountSkuId 
# Disabled Plans
$disabledPlans= @()
$disabledPlans +="FLOW_O365_P2" 
$licenseOptions = New-MsolLicenseOptions -AccountSkuId $accountID -DisabledPlans $disabledPlans;
$licensedUsers = Get-MsolUser -All | ? {$_.isLicensed -eq "TRUE"}
$licensedUsers | Set-MsolUserLicense -LicenseOptions $licenseOptions

This would enable anything else that was previously disabled.

In summary, I needed to loop through existing disabled licences and add to $disabledPlans before I could set the licenses.  Here is the code to disable PowerApps and Flow (apologies about the formatting).

# $cred = Get-Credential 
# Connect-MsolService -Credential $cred 
$licensedUsers = Get-MsolUser -All | ? {$_.isLicensed -eq "TRUE"} 
ForEach ($licensedUser in $licensedUsers) 
{
Write-Host "---------------------------------" 
Write-Host "UserPrincipalName-"$licensedUser.UserPrincipalName 
$accountSku = $licensedUser.Licenses.AccountSkuId 
Write-Host $accountSku 
# Disabled Plans 
$disabledPlans= @() 
$disabledPlans +="FLOW_O365_P2" 
$disabledPlans +="POWERAPPS_O365_P2" 
$licensesAssigned = $licensedUser.Licenses.ServiceStatus 
foreach ($serviceStatus in $licensesAssigned) 
{ 
# A bit of logic to check if its not already disabled as we don't want to add twice 
if($serviceStatus.ProvisioningStatus -eq "Disabled")
{
$planName = $serviceStatus.ServicePlan.ServiceName 
Write-Host "Already Disabled - "$planName 
if($planName -eq "FLOW_O365_P2" -or $planName -eq "POWERAPPS_O365_P2") 
{
# Do nothing as already added above
}
else
{
# Add to array as we want to keep it disabled 
$disabledPlans += $planName
}
}
}
# Now ready to create license Options and disable plabs for that user 
Write-Host "Disabling following licenses for user" 
Write-Host $disabledPlans
$licenseOptions = New-MsolLicenseOptions -AccountSkuId $accountSku -DisabledPlans $disabledPlans; 
Set-MsolUserLicense -UserPrincipalName $licensedUser.UserPrincipalName -LicenseOptions $licenseOptions
}

 

About the author 

Qamar Zaman