Find text (string) in text file(s)
If you want to find a certain text (string) in a text file or multiple text files, the quickest way to do so, is by using the select-string option.
First you’d need to get a list of the files you want to search trough:
$FileList = Get-ChildItem -Path "D:\temp\"
or you can use it on a single file as well
$FileList = Get-ChildItem -Path "D:\temp\file.txt"
After that, you can use select-string to find all files which contains the string you like to search for (in this case I’m searching for the text ‘success’):
$Success = $FileList | Select-String -Pattern 'success'
The variable $Success now has the following properties:
Out of which these are usually the most interesting ones in this kind of search:
Line (the text in the line select-string found the text you’re searching for)
Path (path & file name to the file)
Searching through a directory with about 50 files, which have a total size of 12,6MB and over 200.000 matches, only took 2 seconds this way. As far as I know, this is the quickest way to search through files with PowerShell.
Instead of a simple text search, you can also direct the select-string cmdlet to detect multiple matches per line, display text before and after the match, or display only a Boolean value (True or False) that indicates whether a match is found. Select-String uses regular expression matching, but it can also perform a simple match that searches the input for the text that you specify; like in my example above.
Have fun using this great and quick cmdlet. If you know of any quicker and easier ways to find text or patterns in files, let me know in the comments below and maybe my next blog post will be about that.
Remember that those who forget to script, are doomed to repeat their work!