remove all licenses from a user in O365

Hi,
I’m trying to remove all the licenses from a given user in 0365

when I try to execute this code
[pre]
$csvFileLocation = “c:\temp\csv\toRemove.csv”
$users = Import-Csv -Path $csvFileLocation
foreach ($user in $users) {
$upn = $user.UserPrincipalName
(get-MsolUser -UserPrincipalName $upn).licenses.AccountSkuId |
foreach{
Set-MsolUserLicense -UserPrincipalName $upn -RemoveLicenses $_
}
}[/pre]
then I get this error

[pre]
Set-MsolUserLicense : Unknown error occurred.
At line:5 char:9

  • foreach{Set-MsolUserLicense -UserPrincipalName $upn -RemoveLicenses $ …
  • CategoryInfo : OperationStopped: (:slight_smile: [Set-MsolUserLicense], MicrosoftOnlineException
  • FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.InvalidOperationOnGroupInheritedLicenseException,Microsoft.Online.Administration.Automation.Set
    UserLicense
    [/pre]

 

how do I solve this?

 

Paul

 

According to the help this should be enough:

$csvFileLocation = 'c:\temp\csv\toRemove.csv'
$users = Import-Csv -Path $csvFileLocation
foreach ($user in $users) {
    $Licenses = (Get-MsolUser -UserPrincipalName $user.UserPrincipalName).licenses.AccountSkuId
    Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -RemoveLicenses $Licenses
}

Hi Olaf,

When I try your code I get this error

[pre]

Set-MsolUserLicense : Unknown error occurred.
At line:5 char:5

  • Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -R …
  • CategoryInfo : OperationStopped: (:slight_smile: [Set-MsolUserLicense], MicrosoftOnlineException
  • FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.InvalidOperationOnGroupInheritedLicenseException,Microsoft.Online.Administration.Automation.Set
    UserLicense

[/pre]
which seems to be the same as mine by the looks of it

 

Paul

Hmmm … did you assign the licenses through a group membership or direct?

Hello Paul,

What type of license you have on the tenant?

Some licenses need to be removed before the others, as they might be dependent on each other.

Please review following thread:

https://techcommunity.microsoft.com/t5/office-365/error-when-trying-to-remove-a-license/m-p/308969

Olaf,
I know that for the Office365 the user is put in a security group in AD to be able to use office when I look up the same user in AzureAD then I see this info if this is usefull to you

Communications Credits
Active
1/1
Inherited (Office365License-Users)
Enterprise Mobility + Security E5
Active
9/9
Inherited (Office365License-Users)
Office 365 E5
Active
36/39
Inherited (Office365License-Users)
 

or do I need to remove the licenses directly from azureAD?

 

Update:

removing the license from on Prem AD sorted this out

 

Paul

 

You can remove the licenses this way only when you assigned them directly. … it’s a kind of logic … when you remove the license while the according group membership is still “active” the license will “come back”. :wink: