Select String by Pattern in Windows PowerShell

Q

How to select strings with a given pattern in Windows PowerShell? I want to find some specific text in strings.

✍: FYIcenter.com

A

You can use the "Select-String" cmdlet to do string pattern match in Windows PowerShell.

The Select-String cmdlet searches for text and text patterns in input strings and files. You can use it like Grep in UNIX and Findstr in Windows. You can type "Select-String" or its alias, "sls".

Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match. However, you can direct it to detect multiple matches per line, display text before and after the match, or display only a Boolean value (true or false) that indicates whether a match is found.

Select-String uses regular expression matching, but it can also perform a simple match that searches the input for the text that you specify.

Select-String can display all of the text matches or stop after the first match in each input file. It can also display all text that does not match the specified pattern. You can also specify that Select-String should expect a particular character encoding, such as when you are searching files of Unicode text.

Example 1:

    PS C:\>select-string -path *.xml -pattern "the the"

This example searches through all files with the .xml file name extension in the current directory and displays the lines in those files that include the string "the the".

Example 2:

    PS C:\>$events = get-eventlog -logname application -newest 100
    PS C:\>$events | select-string -inputobject {$_.message} -pattern "failed"

This example searches for the string "failed" in the 100 newest events in the Application log in Event Viewer.

The first command uses the Get-EventLog cmdlet to get the 100 most recent events from the Application event log. Then it stores the events in the $events variable.

The second command uses a pipeline operator (|) to send the objects in the $events variable to Select-String. It uses the InputObject parameter to represent the input from the $events variable. The value of the InputObject parameter is the Message property of each object as it travels through the pipeline. The current object is represented by the $_ symbol.

As each event arrives in the pipeline, Select-String searches the value of its Message property for the "failed" string, and then displays any lines that include a match.

 

Work with Strings in Windows PowerShell

⇒⇒Windows PowerShell Tutorials

2016-10-19, 773👍, 0💬