I wanted to filter out or exclude the two or more licenses assigned to the user by using the below simple query, but it is not doing anything.
The line below still includes the two licenses described in the $Skip variable:
#License to ignore
$Skip = 'M365_E5', 'FLOW_FREE'
$SKU = @(Get-MgUserLicenseDetail -UserId 'Username@domain.com') |
Where-Object { $_.SkuPartNumber -notcontains $Skip }
The -[not]contains
operator(s) is for collection containment - whereas you want to perform one or more substring searches, preferably using the -like
or -match
operators.
To if any of a given number of terms is found as a substring in a given input string, use the .Where()
extension method in First
-mode:
... |Where-Object { $SkuPartNumber = $_.SkuPartNumber; @($Skip).Where({$SkuPartNumber -like "*$_*"}, 'First').Count -eq 0 }
If any of the strings in $Skip
is found in the part number, the Count
of the resulting value will be greater than 0 and the object won't filter through.
As an alternative approach, you could also construct a regex pattern matching either term and use that with the -notmatch
regex operator:
# generate a valid regex pattern in the form (?:term1|term2|...|termN)
$SkipPattern = '(?:{0})' -f $($Skip.ForEach({[regex]::Escape($_)}) -join '|')
Then:
... |Where-Object { $_.SkuPartNumber -notmatch $SkipPattern}