Grep in PowerShell

When I start to use PowerShell, I miss grep in bash. Luckily, PowerShell provides Get-ChildItem and  Select-String.

Some helpful parameters in Select-String are -Pattern and -Path.

Both -Pattern and -Path accept a list of string. Each item is separated by comma, for example, *.txt, *.log

-Pattern is the pattern of text you want to search

-Path is the list of files you want to search.

However, Select-String doesn’t search files under a directory. You have to pass file paths to it via -Path. We can use Get-ChildItem to get a list of files, and get all files under a directory recursively by using -Recurse

The basic pattern to use both cmdlet for greping is as follow:

Get-ChildItem -Recurse -Path C:\Path\To\Folder -Include *.txt | Select-String “SearchText”

I create a script in my GitHub ( so that I can reuse it.

This script is not signed though. If you want to use it, you need to change your execution policy to allow it to run. See Set-Execution.


Leave a Comment

Your email address will not be published. Required fields are marked *