Remove direct assignment from users already inheriting licenses from groups using PowerShell

Wrote a little script to remove double licensing from users both having it directly assigned as well as inherited through a group. This is usefull for when transitioning to group based licensing.

$users = Get-MsolUser -All | ? isLicensed
$i = 0
foreach($user in $users){
$percentageComplete = [math]::Round($i / $users.count * 100, 2)
Write-Progress -Activity "Processing user $i out of $($users.count)" -Status "$percentageComplete% Complete:" -PercentComplete $percentageComplete
$Licenses = $user.Licenses
foreach($License in $Licenses){
if(($license.GroupsAssigningLicense.count -ge 2) -and ($license.GroupsAssigningLicense.Guid -contains $user.ObjectId)){
"$($License.AccountSkuId) is double licensed for user $($user.DisplayName + "(" + $user.userPrincipalName +")") removing direct assignment"
$user | Set-MsolUserLicense -RemoveLicenses $License.AccountSkuId
}
}
$i++
}

    Leave a Reply

    Your email address will not be published. Required fields are marked *