PowerShell Grep (Select-String) Tutorial

One of the most popular and useful commands for Linux is the grep command. The grep command is used to filter file contents for the specified terms and match conditions. PowerShell is the next-generation command-line interface for the Windows operating systems and tries to mimic some popular Linux features and command like grep. Windows PowerShell provides the Select-String command in order to provide the Linux grep command function. In this tutorial, we examine how to use the Select-String command similar to the grep command.

Match Pattern

We start with a simple example where we match a simple pattern. We search the term ” user” in the files located under the ” c:\logs\”. The -Pattern option is used to specify the term we want to search. The -Path option is used to specify the path we want to search.

PS> Select-String -Pattern "user" -Path "C:\logs"

Select Specified Match

A Select-String command may match single or multiple lines where all of them are listed by default. We can use The Select-Object command in order to select specific matches. The -First option is used to list a specified number of matches from the beginning. In the following example, we select the first 5 matches.

PS> Select-String -Pattern "user" -Path "C:\logs" | Select-Object -First 5

Match One Of the Multiple Patterns

Another useful case is mathcing one of the provided multiple patterns. The terms are provided with the -Pattern option and separated with commas. In the following example we search one of the “user”,”admin” and “root”.

PS> Select-String -Pattern "user","admin","root" -Path "C:\logs"

Match Specified Regex

Like grep command the Select-String command can be used to match specified Regex. The regex term is simply provided with the -Pattern option. In the following example we match the IP address regex.

PS> Select-String -Pattern "\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b" -Path "C:\logs"

Match Number Format

The regex can be also used to match different number formats. In the following example we check the “ddd-ddd” number format.

PS> Select-String -Pattern "\d\d\d-\d\d\d" -Path "C:\logs"

Match Case Sensitive

By default the Select-String command is case insensitive. But we can use the -CaseSensitive option in order to match contents in a case sensitive manner.

PS> Select-String -Pattern "user","admin","root" -Path "C:\logs" -CaseSensitive

List Non-Matched Lines

By default the Select-String command lists the matches lines for the provided pattern or regex. But we can reverse the case and list non-matched lines by using thje -NotMatch option.

PS> Select-String -Pattern "user","admin","root" -Path "C:\logs" -NotMatch

Leave a Comment