Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PowerShell select-string to find more than one pattern in a file?

Tags:

powershell

I would like to search for more than one string in the files in a directory, however using "select-string -pattern" didn't help. Could anyone show me how to do it?

Example: Search all files in C:\Logs that contain the words "VendorEnquiry" and "Failed", and with a Logtime about 11:30 am. Structure of files may differ (e.g. different tag names, etc):

... <methodException>VendorEnquiry</methodException> ... ... <logTime>13/10/2010T11:30:04 am</logTime> ... ... <status>Failed</status> ...  ... <serviceMethodException>VendorEnquiry</serviceMethodException> ... ... <logTime>13/10/2010</logTime> ... ... <serviceStatus>Failed</serviceStatus> ... 

Thanks.

like image 862
Thomas Avatar asked Oct 13 '10 02:10

Thomas


People also ask

How do I select multiple strings in PowerShell?

To search for multiple matches in each file, we can sequence several Select-String calls: Get-ChildItem C:\Logs | where { $_ | Select-String -Pattern 'VendorEnquiry' } | where { $_ | Select-String -Pattern 'Failed' } | ...

Can you grep in PowerShell?

When you need to search through a string or log files in Linux we can use the grep command. For PowerShell, we can use the grep equivalent Select-String . We can get pretty much the same results with this powerful cmdlet. Select-String uses just like grep regular expression to find text patterns in files and strings.

How do I search for a string in PowerShell?

You can use it like Grep in UNIX and Findstr in Windows with Select-String in PowerShell. 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.

What does select-string do in PowerShell?

You can direct Select-String to find multiple matches per line, display text before and after the match, or display a Boolean value (True or False) that indicates whether a match is found. Select-String can display all the text matches or stop after the first match in each input file.


1 Answers

If you want to match the two words in either order, use:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)' 

If Failed always comes after VendorEnquiry on the line, just use:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)' 
like image 132
Rynant Avatar answered Sep 27 '22 23:09

Rynant