Reputation: 69
I'm trying to remove multiple licences from a user or users within my .xlsx
file. Here is my code
$users = Import-XLSX '\\server\c$\User Creation\ADUsersRemoval.xlsx' |
where {$_.isLicensed -eq $true}
foreach ($user in $users)
{
$Firstname = $User.Firstname
$Lastname = $User.Lastname
$upn= "[email protected]"
Set-MsolUserLicense -UserPrincipalName $upn -RemoveLicense "Domain:POWER_BI_STANDARD","Domain:FLOW_FREE"
}
I keep getting the error
Set-MsolUserLicense : Unable to assign this license because it is invalid. Use the Get-MsolAccountSku cmdlet to retrieve a list of valid licenses.
Personally I think its because some users may not have one of those licences. If I want to remove one licence and they all had the same licence it would work fine but with two licences and some users don't have both, it just throws up the error.
Any help on this would be appreciated.
Upvotes: 1
Views: 1408
Reputation: 25051
If you are trying to remove a valid license string from a user who does not have the license assigned, it will produce the error you see. You will need to build in logic to only remove licenses that are assigned.
You can do this with Compare-Object
, but it requires an additional query for user information using Get-MsolUser
. If you already have user license assignment in your excel file, then this can be tweaked to run a lot quicker.
$users = Import-XLSX '\\server\c$\User Creation\ADUsersRemoval.xlsx' |
where {$_.isLicensed -eq $true}
$Licenses = "Domain:POWER_BI_STANDARD","Domain:FLOW_FREE"
foreach ($user in $users)
{
$Firstname = $User.Firstname
$Lastname = $User.Lastname
$upn= "[email protected]"
$LicensesToRemove = (Get-MsolUser -UserPrincipalName $upn).Licenses.AccountSkuId |
Compare-Object $Licenses -IncludeEqual -ExcludeDifferent -PassThru
Set-MsolUserLicense -UserPrincipalName $upn -RemoveLicenses $LicensesToRemove
}
Explanation:
$Licenses
contains all of the licenses you'd like to remove. During your foreach
loop, a new variable $LicensesToRemove
will represent the assigned licenses that match your $Licenses
items.
Compare-Object
is used to provide the value to LicensesToRemove
. -IncludeEqual -ExcludeDifferent
ensures that we only output licenses that match in the user's assigned licenses and the licenses you want to remove. -PassThru
allows for only the matched license text string to be output.
Depending on the size of your user list, there will be a point where it is beneficial to collect user license assignment before entering your loop. Running Get-MsolUser
and Set-MsolUserLicense
in each iteration could be less efficient than one all-encompassing Get-MsolUser
before entering the loop.
Upvotes: 2