1

i would like to know how to find UPN that constain digit with -filter?

Get-ADUser -filter {(UserPrincipalName -contains "I dont know what i should add here @contoso.com")} -properties userprincipalname | select userprincipalname
mklement0
  • 382,024
  • 64
  • 607
  • 775
ak2595
  • 301
  • 1
  • 3
  • 16
  • `Get-ADUser` uses Powershell expressions for filters (as contrasted with WQL, a SQL subset). If you had a random string - not necessarily a `UserPrincipalName` from an `ADUser` object - that looked like "Smith123@contoso.com", how would you do it? – Jeff Zeitlin Aug 05 '22 at 19:35
  • @JeffZeitlin, they're _similar_ to PowerShell expressions, but much more limited, with subtle differences in behavior - they're not sophisticated enough to do what is required here. – mklement0 Aug 05 '22 at 19:50
  • As an aside: the `-Filter` language doesn't support the `-contains` operator, only PowerShell does. However, there it does _not_ look for substrings, it tests if an _array_ contains a given element _as a whole_ - see [the docs](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Comparison_Operators#-contains-and--notcontains). – mklement0 Aug 05 '22 at 20:11
  • 1
    @mklement0 - point taken - although that implies that he _can't_ use `-match`, which was what I was thinking of, more-or-less combining your `Get-ADUser` and `Where-Object` into the filter. – Jeff Zeitlin Aug 05 '22 at 23:56

1 Answers1

2

The -Filter argument of AD cmdlets, which accepts a string, uses PowerShell-like syntax, but with only a limited subset of supported operators, some of which work in subtly different ways than in PowerShell.

The filter language is not sophisticated enough to do the matching you want: the only pattern matching supported is via wildcards, which are limited to use of *, using the -like operator.[1]

Therefore, use -Filter for pre-filtering with -like, then use a Where-Object call to let PowerShell filter the results down, using its regex capabilities:

Get-ADUser -Filter 'UserPrincipalName -like "*@contoso.com"' -Properties UserPrincipalName | 
  Where-Object UserPrincipalName -match '\d'
  Select-Object UserPrincipalName

Note:

  • -match '\d' matches if at least one digit (\d) is present in the input.

  • I've used a string rather than a script block ({ ... }) to specify the -Filter argument, because that's what -Filter expects. While seductively convenient, the use of script blocks is conceptually problematic and can lead to misconceptions - see this answer.


[1] By contrast, PowerShell's -like operator supports PowerShell's more fully-featured wildcard expressions. Also, the AD -Filter's language at least situationally interprets * to mean: at least one character, whereas PowerShell's wildcard expression interpret it as zero or more.

mklement0
  • 382,024
  • 64
  • 607
  • 775