SOLVED

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 |
foreach{
Set-MsolUserLicense -UserPrincipalName $upn -RemoveLicenses $_
}

 

This Does work but doesnt work in this script:

 

$upn = '365.test1@domain.com'
(get-MsolUser -UserPrincipalName $upn).licenses.AccountSkuId |
foreach{
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: @{UserPrincipalName=365.test1@domain.com.au}.
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)
Solution

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

 

$upn.UserPrincipalName

 

or set the value like this:

 

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

Thankyou so much

 

That was exactly what i needed

 

@Vasil Michev 

1 best response

Accepted Solutions
best response confirmed by Lucky1998 (Copper Contributor)
Solution

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

 

$upn.UserPrincipalName

 

or set the value like this:

 

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

View solution in original post