In Linux/Unix, the grep command is used to find a text (string) or errors in a log file. Grep allows you to find/select any data in the output of another command:
command | grep search
In PowerShell, you can use the Select-String cmdlet to find a text string in a file.
For example, the following command displays all lines containing ERROR in a text file or stdout:
Select-String -Path c:\tmp\makeapp_sxtracesxs.txt -Pattern "ERROR"
The command has shown the number of lines that contain the text you are looking for and their values.
If you want to search for a string in all
TXT files in a specific directory, run the command below:
Select-String -Path c:\tmp\*.txt -Pattern "ERROR"
You can use this command if you want to search through all files in a folder. For example, this command can be useful for searching transport (SMTP) and message tracking logs on Exchange Server.
Using the Exclude and Include options, you can include or exclude certain files for search. The following command will search through all TXT and LOG files that do not contain copy in their names:
$path = "c:\tmp\*"
Select-String -Path $path -Pattern "ERROR" -Include "*.txt","*.log" -Exclude "*copy*"
The previous example searches for a text in the specified directory only. To search files in the nested directories recursively, use the Get-ChildItem cmdlet:
Get-ChildItem -Path 'c:\tmp\' -Recurse -include "*.mp3","*.avi" -ErrorAction SilentlyContinue | Select-String -SimpleMatch "ERROR","WARNING"