1

I want to filter only files and folders with name start with 2[A-Z] (uppercase only):

ls -recurse | Where-Object {$_.name -match '2[A-Z]'}

But it still returns lowercase files. Reading the -match parameter of Where-Object I don't see a way to fix this.

Ooker
  • 1,969
  • 4
  • 28
  • 58
  • 1
    As an aside: Your doc link describes the `-Match` _parameter_ of the `Where-Object` cmdlet, which, when using [simplified syntax](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Simplified_Syntax), refers to the [`-match` _operator_](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Comparison_Operators#-match-and--notmatch), which exists independently of the cmdlet. – mklement0 Dec 25 '22 at 06:12
  • Does this answer your question? [How to do a case-sensitive file search with PowerShell?](https://stackoverflow.com/questions/26432076/how-to-do-a-case-sensitive-file-search-with-powershell) – zett42 Dec 25 '22 at 11:45

1 Answers1

1

PowerShell's comparison operators are case-insensitive by default, but they have c-prefixed variants that are case-sensitive, namely -cmatch in the case of the -match operator:

gci -recurse | Where-Object { $_.Name -cmatch '^2[A-Z]' }
  • gci is used as the PowerShell-idiomatic alternative to the Windows-only ls alias for Get-ChildItem.

    • See the bottom section of this answer for more information on why aliases named for commands or utilities of a different shell or platform are best avoided.
  • Regex assertion ^ is used to ensure that the pattern only matches at the start of file names.


Alternatively, use simplified syntax:

gci -recurse | Where-Object Name -cmatch '^2[A-Z]'
mklement0
  • 382,024
  • 64
  • 607
  • 775