Powershell command in batch file: Remove all lines from text file except lines with "foo" and "bar"?

Just use two separate conditions joined with OR:

cat $_.FullName | ? { $_ -like '*foo*' -or $_ -like '*bar*' }

Parentheses can be used to add clarity, but they're optional:

{ ($_ -like '*foo*') -or ($_ -like '*bar*') }

post a batch file command just like I have above. Please don't tell me to swap over to using ps1 scripts or give answers that are explaining what to type into a console window.

Those are literally the same thing. It doesn't matter how you invoke a PowerShell script – whether it's stored in a file or passed through the command line or input by keyboard, it's still a PowerShell script and it follows the same syntax rules.


You can use select-string instead which takes regular expressions:

gci *.txt | % { (cat $_.FullName | select-string -pattern 'foo|bar') | set-content $_.FullName -Force }

select-string allows you to perform more complicated regular expression matching going forward if you need to.


Further Reading

  • Regular Expressions - PowerShell - SS64.com
  • Select-String - PowerShell - SS64.com