PowerShell Search File For Pattern

PowerShell provides functionality to search the contents of one or more files for a pattern. The Select-String cmdlet enables us to achieve this goal. Let’s consider the following simple file with the contents:

1
2
3
4
5
This is line number 1
This is line number 2
This is line number 3
This is line number 4
This is line number 5

We would like to search for the text “This is line number 5”.

1
Select-String -Simple "This is line number 5" .\text.txt

Above we use the -Simple parameter of the Select-String cmdlet. This parameter allows us to perform a case insensitive exact match for the text “This is line number 5”. We must also enclose our search term in quotes as it contains space characters. If we did not escape the search term PowerShell would misinterpret our command, resulting in an error. The above command outputs the matching lines along with the name of the file and the line number.

1
text.txt:5:This is line number 5

The Select-String cmdlet provides a quick and easy method to search for text within a file. We can also use the Select-String cmdlet to search using a regular expression.

1
Select-String "^.*5$" .\text.txt

The above command searchs for any line of text ending with the number 5.

1
text.txt:5:This is line number 5

Conclusion

In this small tutorial we looked at how we can use Powershell to search a file for a pattern.