Azure AD – Remove licenses via PowerShell

The Azure AD Powershell cmdlets are a bit quirky. They don’t behave like regular PowerShell cmdlets don’t (they don’t seem to work with switches like -Verbose or -ErrorAction for instance) and in general seem to be wrappers for some API requests that run behind the scenes. I am thankful they exist of course, coz the last thing I want to do is make API queries, but it would be nice if they behaved better.

Here’s one quirk I ran into today. I wanted to remove licenses from a bunch of users. There’s a cmdlet Set-AzureADUserLicense and it’s well documented too with an example:

Basically you find a user who already has the licenses you are interested in assigned to them and set these to a variable (that’s lines 1-3 above). This variable is called $License above and is of type Microsoft.Open.AzureAD.Model.AssignedLicense. Then you define a new variable (called $Licenses) of type Microsoft.Open.AzureAD.Model.AssignedLicenses and assign the licenses captured in the $License variable to this via an AddLicenses() method (lines 5 &6).

Finally you assign this to user. Straightforward.

I wanted to remove licenses so I figured why not do the same but in reverse.

The $Licenses.SkuID property seems to be a string. It looks to be something like this for an example user:

That’s three GUIDs corresponding to three licenses this user has. Say I want to remove the first of these licenses, so all I really need to do is the following:

Now let’s create the $Licenses variable as before and set the above to be removed:

So far so good. Now let me go ahead and set this for a user:

But that doesn’t work! I get the following error:

First I thought maybe it was something to do with my manually removing a license from the variable. Maybe it looks like a string but not really a string and I messed something up. So I tried removing all licenses without any changes and still got the same error.

Then I realized the error message says: Cannot convert a primitive value to the expected type ‘Edm.Guid‘.

Hmm, sounds like wants a GUID instead of the object I was passing. What if I change things a bit to pass the GUIDs? Actually, a single GUID… coz it expects that and not an array of them. Here we go:

And that worked! So it turns out removing licenses works differently to adding licenses. When adding you need to pass an object, while for removing you pass the GUID. Also, I don’t really need to get the license object from an existing user… all I need is the GUIDs of the licenses I want to add or remove.

So here’s my adding and removing licenses just to show the difference:

Update: After writing this post I looked at the properties of the Microsoft.Open.AzureAD.Model.AssignedLicenses object and to be fair it does show the two methods as being different. My bad for not examining this to begin with.

And it looks like RemoveLicenses too takes an array. So I can pass it multiple GUIDs.