PowerShell: Search String in Files

By Xah Lee. Date: . Last updated: .

Here's ways to search a string in file content of files in a dir. (like linux grep)

Search by regex

List all occurences of regex pattern of the content of html files in a directory:

dir * -recurse -include *.html | sls "joe|jane"

Note: when you use -include, you must list by dir content, e.g. dir * or with -recurse

Search by Literal String

Match by literal string, use SimpleMatch:

dir * -recurse -include *.html | sls "abc" -SimpleMatch

Case Sensitive Search

dir * -recurse -include *.html | sls "abc" -SimpleMatch -CaseSensitive

Multiple Search Patterns

dir * -recurse -include *.html | sls regex1, regex2

Common Select-String parameters

Match as literal string on value of -pattern. (by default, the -pattern is interpreted as regex)
Case sensitive. (by default, it's case-insensitive)
Find all matches in a line. (by default, only first match in a line is found.) This parameter is ignored when used in combination with the SimpleMatch parameter. To absolutely get all matches, don't use the SimpleMatch parameter. Escape your -pattern value instead. See about_Regular_Expressions.
List lines that do not match.

Note: Select-String tries to match string by line units in input text. You cannot use it to search block of text that contains newline character.




Script Examples