Shell – Powershell – filenames that match two (or more) patterns

powershell

To find files in a directory that have both "foo" and "bar" in the filename, we can use:

Get-ChildItem | Where-Object {$_.Name -like "*foo*" -and $_.Name -like "*bar*"}

Is there a more elegant way to write (or query for) this?

Best Answer

Why do you consider your command inelegant? If you're just after more terse code, this might be better on Code Review.

Incidentally, I don't think that command would work.

If you want to use -like, then add wildcards:

gci | ? {$_.Name -like "*foo*" -and $_.Name -like "*bar*"}

If you don't want to use wildcards, use -match:

gci | ? {$_.Name -match "foo" -and $_.Name -match "bar"}

There are many ways to skin a cat

gci *foo* | ? {$_.Name -in (gci *bar*).Name}

I think more elegant code is subjective and really depends on your coding style. I personally prefer your line of code as it's not cryptic at all, and it's fairly compact for what it does.

Related Question