1

I am trying to get a users assigned Licenses.

Using Get-MsolUser -UserPrincipalName $UPN |Format-List Licenses I have a list that looks something like this: Licenses : {testmailorg:FLOW_FREE, testmailorg:M365EDU_A3_FACULTY}

I want be able to get the licenses from this as an individual strings such as "M365EDU_A3_FACULTY"

So far I have been unable to achieve this using foreach or for loops.

Is there anyway to do this, or even a different way to get users Licenses?

Thanks

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • 1
    Do you mean `(Get-MsolUser -UserPrincipalName $UPN).Licenses` ? – Theo Mar 14 '21 at 13:06
  • 1
    the code posted by Theo will give you the values as strings in an array [if there is more than one]. once you have that, you can split on the `:`, take the last part, and `-join ','` to have a coma delimited string with all those values. – Lee_Dailey Mar 14 '21 at 14:01

1 Answers1

0

First, to be clear: Format-* cmdlets output objects whose sole purpose is to provide formatting instructions to PowerShell's output-formatting system - see this answer. In short: only ever use Format-* cmdlets to format data for display, never for subsequent programmatic processing.

Here, the formatted output tells you that the information of interest is contained in the .Licenses property, so, as Theo points out, you can simply access the property value by enclosing the command in (), the grouping operator:

# Outputs the .Licenses property value of the object output by Get-MsolUser.
(Get-MsolUser -UserPrincipalName $UPN).Licenses

As the property name (and the formatted output) implies, .Licenses contains a collection of objects (possibly strings), and to extract only the part of each (stringified) object after the testmailorg: prefix, you need to use text parsing, as Lee Dailey advises; here, the simplest approach is to use PowerShell's regex-based -replace operator, which can directly operate on collections and performs string replacement on each element:

PS> (Get-MsolUser -UserPrincipalName $UPN).Licenses -replace '^.+:'
FLOW_FREE
M365EDU_A3_FACULTY

Note: If the LHS is a collection (array), the result of the -replace operation is a corresponding array ([object[]]) of the transformed strings.

mklement0
  • 382,024
  • 64
  • 607
  • 775