Sometimes it can be necessary to search for a string in a text or log file while this operation is rather easy using an editor like Notepad I usually find it easier and faster to use PowerShell for the task.
Let’s assume you have a log file named MyLogFile.log and you would like to find all occurrences of a specific string or pattern you can easily achieve this through the following command:
# Search for string HeloCheck in MyLogFile.log file Select-String -Path .MyLogFile.log -Pattern HeloCheck # Which will produce a result like the one below MyLogFile.log:2:HeloCheck MyLogFile.log:3:Lethe HeloCheck MyLogFile.log:4:HeloCheck Blog
As you can see above PowerShell will search the string in the file indicated by the -path switch and will output the file name where the string has been found, the line number and the string itself, as an image is worth more than thousand words here’s the output on my test machine:
In the above example we’ve scanned a single file for a specific string but what if we need to search a string in multiple files? Well simply pass them to the -path switch like this:
#PowerShell search string in multiple files Select-String -Path .MyLogFile.log, .MyOtherLog-1.LOG -Pattern Helocheck # You can even use a match all character like this Select-String -Path .MyLo* -Pattern Helocheck
If you take a minute to read through the man (sorry old Unix habits) page for the Select-String cmdlet you will also find that you can search multiple strings simply separating the pattern with a comma:
#PowerShell search multiple strings in a log file Select-String -Path .MyLogFile.log, -Pattern Helocheck, Lethe # Will return MyLogFile.log:2:HeloCheck MyLogFile.log:3:Lethe MyLogFile.log:4:HeloCheck Blog MyLogFile.log:9:.....Lethe
As you can see the Select-String can be used as powerful framework to build script that will use PowerShell to search string in a single or multiple files using both simple patterns or regular expressions, issue a man Select-String to learn all the switches and possibilities made available by this powerful cmdlet.