How to remove office 365 license

Hello Experts,

I need to remove the licenses from my o365 users nightly. (I'll tell why if asked.)
I was trying to use this:
$x = Get-MsolUser -All  | where {$_.isLicensed -eq $true}; $x | foreach {Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -RemoveLicenses "tenant:PROJECTCLIENT_GOV"}

Which should work, but looks ugly failing on 700 accounts and succeeding on the 35 that actually have licenses.
How can I change this statement to return only account licensed to use tenant:PROJECTCLIENT_GOV?

Who is Participating?
Vasil Michev (MVP)Connect With a Mentor Commented:
You can filter by license SKU via:

Get-MsolUser -All | ? {$_.Licenses.AccountSkuId -eq "tenant:PROJECTCLIENT_GOV"}

Open in new window

or whatever the SKU is.
Edward PamiasTeam Lead RRS DeskCommented:
There are a few ways to do this, one is to create a text file and put in the account names then run a powershell script which will handle the rest. See link below from Microsoft with the correct powershell scripts to run.

Click here.
Todd NelsonSystems EngineerCommented:
Take a look at these references.  The first is for assigning licenses but the foundation is there to remove licenses and license options as well.

Let us know.
SMB Security Just Got a Layer Stronger

WatchGuard acquires Percipient Networks to extend protection to the DNS layer, further increasing the value of Total Security Suite.  Learn more about what this means for you and how you can improve your security with WatchGuard today!

glo-nsaAuthor Commented:
The syntax for removing I have down. What I am needing is the filter for only users that already have the named license.

I think there should be a filter condition on the back of this statement:
$x = Get-MsolUser -All  | where {$_.isLicensed -eq $true}

Todd NelsonSystems EngineerCommented:
You can do that to get all of the users that are assigned a license.  Have you tried that?
glo-nsaAuthor Commented:
Perfect! Concise and with relevant example.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.