RoyW
RoyW

Reputation: 65

PowerShell Set-MSolUserLicense

I am trying to unassign a bulk of user's licenses from our Office365.

I have all of the user's UserPrincipalName on a CSV file like so:

Name
[email protected]
[email protected]
"
"

That is what I tried to do:

$csv1 = import-csv | select -expandProperty name

Set-MsolUserLicense -UserPrincipalName $csv1 -RemoveLicense "domain:STANDARDPACK"

When I had only one user on the CSV file, it works! But when I try to add more users to the exact file and in the exact same list, the command fails and give me this error:

Set-MsolUserLicense : Unable to assign this license because it is invalid. Use the
Get-MsolAccountSku cmdlet to retrieve a list of valid licenses.

I doubled checked and made sure the it is indeed the correct license (domain:StandartPack)

What else can I do? How can I make it work?

Upvotes: 2

Views: 4817

Answers (2)

Avshalom
Avshalom

Reputation: 8889

You need to iterate each line in the csv at a time, at the moment you work with all of them at once, so try this:

$csv1 = import-csv | select -expandProperty name
foreach ($upn in $csv1)
{
Set-MsolUserLicense -UserPrincipalName $upn.Name -RemoveLicense "domain:STANDARDPACK"
}

**EDIT:

Try the following method as well (update if necessary)

$csv1 = import-csv | select -expandProperty name
foreach ($upn in $csv1)
{
$License = Get-MsolUser -UserPrincipalName $upn.Name | % {$_.Licenses.AccountSkuId}
    if ($License) {
    Set-MsolUserLicense -UserPrincipalName $upn.Name -RemoveLicense $License
    }
}

Upvotes: 4

Powershell Dave
Powershell Dave

Reputation: 21

You will need to iterate through all of the licenses assigned and find the one you are looking to remove.

foreach($UPN in $csv1){
  $user = Get-MsolUser -UserPrincipalName $UPN
  $license_Count = ($user.licenses).count

  for($e=0;$e -le $license_Count - 1;$e++){
    if($user.Licenses[$e].AccountSkuID -eq "domain:STANDARDPACK"){
      Set-MsolUserLicense -UserPrincipalName $user -RemoveLicenses "domain:STANDARDPACK"
    }
  }
}

Upvotes: 0

Related Questions