PowerShell is a powerful tool that can be used to grep text from a file. To use PowerShell to grep text from a file, you first need to create a new instance of the PowerShell cmdlet. Then, you can use the -g flag to specify the type of search you want to perform. The following example uses the -g flag to search for all lines that contain the word “password” in a file named “password.txt”. PS C:> $file = “password.txt” PS C:> $result = $file .split(",") PS C:> $lines = $result .split(",") PS C:> foreach ($line in $lines) { echo “$line: ‘$($_.replace(‘password’,’!’))’” } password: ‘!
grep is a powerful text searching utility on Linux, but it isn’t available on Windows. While there are third party ports and solutions, PowerShell offers built-in equivalents to grep that will do the same job in your scripts.
Using findstr to grep Search In PowerShell
There are a couple different search utilities in PowerShell, each with their own strengths. The simplest is findstr, which is a native windows executable. This works well to replace grep for simple search operations at the command line. For example, you can pipe the output of ls to it to find matches.
You can also search for multiple words at a time, use wildcards to match anything, and use the /R flag to pass basic regular expressions.
Though, if you want to explicitly search including a space, you’ll need to use the /C: flag:
If you’re used to the Linux command line, and don’t want to remember a new command, you can configure “grep” to be an alias to findstr, which will let you keep your muscle memory.
Using Select-String to grep Search in PowerShell
The other native method PowerShell offers is the Select-String cmdlet, which does a lot of the same things as findstr, but is a PowerShell cmdlet instead of a Windows executable.
This means it will work better in PowerShell scripts, and most notably returns its output as an object, which can be pretty-printed by PowerShell. It’s also easier to use on the command line, as PowerShell’s tab completion will work with it.
It works just like findstr, and can take wildcards and regular expressions as well.
You can use Select-String to grep text inside files, by passing it a -Path argument. You can also use it with input passed from other cmdlets like Get-Content.
If you’d like to use it at the command line, you can also alias it to “grep” for quick access.