Powershell equivalent of `grep -r -l` (--files-with-matches)

In Powershell, how do I list all files in a directory (recursively) that contain text that matches a given regex? The files in question contain really long lines of incomprehensible text, so I don't want to see the matching line -- just the filename.


You can use Select-String to search for text inside files, and Select-Object to return specific properties for each match. Something like this:

Get-ChildItem -Recurse *.* | Select-String -Pattern "foobar" | Select-Object -Unique Path

Or a shorter version, using aliases:

dir -recurse *.* | sls -pattern "foobar" | select -unique path

If you want just the filenames, not full paths, replace Path with Filename.


Explanation:

  1. Get-ChildItem-Recurse *.* returns all files in the current directory and all its subdirectories.

  2. Select-String-Pattern "foobar" searches those files for the given pattern "foobar".

  3. Select-Object-Unique Path returns only the file path for each match; the -Unique parameter eliminates duplicates.


Note, that in powershell v1.0 and v2.0 you need to specify first position parameter (path) to work with -Recursion

technet documentation

-Recurse

Gets the items in the specified locations and in all child items of the locations.

In Windows PowerShell 2.0 and earlier versions of Windows PowerShell, the Recurse parameter works only when the value of the Path parameter is a container that has child items, such as C:\Windows or C:\Windows*, and not when it is an item does not have child items, such as C:\Windows*.exe.


Use the below command inside the directory you would like to perform the "grep" and change [SEARCH_PATTERN] to match what you would like to match. It's recursive, searching through all files in the directory.

dir -Recurse | Select-String - pattern [SEARCH_PATTERN]

http://www.jamescoyle.net/how-to/1205-how-to-use-powershell-to-recursively-search-for-text-within-files-on-windows