Correct my powershell please. Set-MsolUserLicence

Copper Contributor

Hey Guys relatively new to Powershell but creating a termination script. all working well and good apart from this section to remove 365 licences.


This is what i want to be able to do but doesn't work:


$upn=Get-ADUser -Identity 365.test1 | Select Userprincipalname
(get-MsolUser -ObjectID $upn).licenses.AccountSkuId |
Set-MsolUserLicense -UserPrincipalName $upn -RemoveLicenses $_


This Does work but doesnt work in this script:


$upn = ''
(get-MsolUser -UserPrincipalName $upn).licenses.AccountSkuId |
Set-MsolUserLicense -UserPrincipalName $upn -RemoveLicenses $_


Seems to be something to do with my first line but i cannot figure it out.


Thankyou in Advance

4 Replies

Any particular error? It looks OK to me.

@Vasil Michev 

tried several variations. 

When i type in the UPN manually like above it works fine but when trying to get it by the Get-AdUser command it doesn't like it. Recognises its there though.


get-MsolUser : User Not Found.  User: @{}.
At line:2 char:2
+ (get-MsolUser -UserPrincipalName $upn).licenses.AccountSkuId |
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [Get-MsolUser], MicrosoftOnlineException
    + FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.UserNotFoundException,Microsoft.Online.Administration.Automation.GetUser



best response confirmed by Lucky1998 (Copper Contributor)

Oh sorry, I thought it was the other way around, my bad. So basically, you need to get just the UPN value, not the object. Either use




or set the value like this:


$upn = Get-AdUser blabla | select -ExpandProperty UserPrincipalName

Thankyou so much


That was exactly what i needed


@Vasil Michev