How to use PowerShell's Grep

Join me as I look at how you can use grep within PowerShell

How to use PowerShell's Grep
How to use PowerShell's Grep

One command that is prominent in Linux system administrators' toolbox is grep.  This tool's core ability is to search plain text for a RegEx pattern.  Grep can search files in a given directory.

In the PowerShell world, do we have that command?  Well, kind of.

Select-String can help search for text or text patterns in input strings and files.   It's very similar to grep or even findstr in Windows.

There are three ways you can use Select-String: pipe in quoted text, use text stored in a variable or use the Path parameter to specify files to search for the text in.


We can search for text within files with the command:

Select-String -Path "*.csv" -Pattern "Rachel"
Select-String Result
Select-String result

The result of this Select-String search is finding the name Rachel within the file twice.

You may want to find an event within a Windows Event Log, and rather than sit and search through it, you can use the Select-String command.

#Let's get the 50 most recent events from the System Log and store the information in the variable events

$Events = Get-WinEvent -Log System -MaxEvents 50

#We send the variable into the Select-String pipeline and it searches for any events that have delete operations in them

$Events | Select-String -InputObject {$_.message} -Pattern 'Delete'
Searching Events Logs with Select-String
Searching Events Logs with Select-String

So the above command collects the last 50 events from the System log, and then, using Select-String, we look for any events that have the string delete in them.

I hope this has given you some inspiration on how to use grep within PowerShell! 👍