How to search a string in multiple files and return the names of files in Powershell?
This should give the location of the files that contain your pattern:
Get-ChildItem -Recurse | Select-String "dummy" -List | Select Path
There are a variety of accurate answers here, but here is the most concise code for several different variations. For each variation, the top line shows the full syntax and the bottom shows terse syntax.
Item (2) is a more concise form of the answers from Jon Z and manojlds, while item (1) is equivalent to the answers from vikas368 and buygrush.
-
List FileInfo objects for all files containing pattern:
Get-ChildItem -Recurse filespec | Where-Object { Select-String pattern $_ -Quiet } ls -r filespec | ? { sls pattern $_ -q }
-
List file names for all files containing pattern:
Get-ChildItem -Recurse filespec | Select-String pattern | Select-Object -Unique Path ls -r filespec | sls pattern | select -u Path
-
List FileInfo objects for all files not containing pattern:
Get-ChildItem -Recurse filespec | Where-Object { !(Select-String pattern $_ -Quiet) } ls -r filespec | ? { !(sls pattern $_ -q) }
-
List file names for all files not containing pattern:
(Get-ChildItem -Recurse filespec | Where-Object { !(Select-String pattern $_ -Quiet) }).FullName (ls -r filespec | ? { !(sls pattern $_ -q) }).FullName