PowerShell Grep Equivalent

The grep command is widely used on Linux to parse files and shell output. By Using grep you can easily find and filter the output returned by the previous command in the pipeline.

In this article, we’ll take a look at the equivalents of the grep command in Windows PowerShell.

On the Windows Command Line (CMD), the equivalent to grep is findstr. However, it is difficult to use it in PowerShell scripts. The simplest PowerShell equivalent to grep is Select-String.

The Select-String cmdlet provides the following features:

  • Search by regular expressions (default);
  • Search by literal match (the parameter -Simple);
  • Search only the first match in the file, ignoring all subsequent ones (the –List switch);
  • Search for all matches, even if there are several of them in one line (-AllMatches);
  • Search for lines that don’t match the pattern (the –NotMatch parameter is similar to the –v switch of the grep tool);

In addition to the directly matched line, display several previous and next lines (the -Context argument);

Select-String allows specifying the encoding of the input file (parameter -Encoding). The following encodings are supported: ASCII, BigEndianUnicode, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32.

List of Open Ports

For example, use the following command to find a list of open ports on your computer (with the Listening status):

Netstat -na | Select-String “LISTENING”

If the previous pipe command returns objects other than the text, use the Out-String –Stream command before passing them to Select-String:

Get-Service | Out-String -Stream | Select-String “Running”

Regular Expressions

You can use the regular expressions (RegEx) in the Select-String cmdlet.

For example, the following command will find all files or lines containing the word “Error” in the specified folder:

Get-Childltem -Path C:\PS | Select-String -Pattern ‘Error’

If you need to check all sub-folders, use the -Recurse parameter:

Get-ChildItem “C:\PS\” -Filter *.log -Recurse | Select-String “Failed”|

To display the names of all found files and matching line numbers:

Get-ChildItem “C:\PS\” -Filter *.log -Recurse | Select-String “Failed”| Select Filename, LineNumber, Line, Path | Format-Table

You can copy all files which match to the specified directory:

Get-ChildItem C:\logs\ -Filter *.log -Recurse | Select-String “Failed”| Copy-Item -Destination C:\Errors

The Select-String cmdlet allows you to process string data. Use the Where-Object cmdlet if you need to grep objects (Filtering PowerShell objects using Where-Object).

For example, you want to find all processes that use more than 300 MB of RAM.

Use this command:

Get-Process | Where-Object { $_.WorkingSet -gt 314572800 }

Leave a Reply

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




Enter Captcha Here :