24/7/365 Support

How to Search a File for Text or a Pattern in Windows PowerShell

Problem

You want to find a string or regular expression in a file.

Solution

To search a file for an exact (but case insensitive) match, use the –Simple parameter of the SelectString cmdlet:

PS >SelectString –Simple SearchText file.txt To search a file for a regular expression, provide that pattern to the SelectString cmdlet:

PS >SelectString "\(...\) ......." phone.txt To Recursively search all *.txt files for a regular expression, pipe the results of GetChildItem to the SelectString cmdlet:

PS >GetChildItem Filter *.txt Recurse | SelectString pattern

Discussion

The SelectString cmdlet is the easiest way to search files for a pattern or specific string. In contrast to the traditional textmatching utilities (such as grep) that support the same type of functionality, the matches returned by the SelectString cmdlet include detailed information about the match itself.

PS >$matches = SelectString "output file" transcript.txt PS >$matches | Select LineNumber,Line

LineNumber Line 7 Transcript started, output file... If you want to search multiple files of a specific extension, the SelectString cmdlet lets you use wildcards (such as *.txt) on the filename. For more complicated lists of files (which includes searching all files in the directory), it is usually more useful to use the GetChildItem cmdlet to generate the list of files as shown previously.

By default, the SelectString cmdlet outputs the filename, line number, and matching line for every match it finds. In some cases, this output may be too much detail— such as when you are searching for which binary file contains a specific string. Binary files rarely make sense when displayed as text, so your screen quickly fills with apparent garbage.

The solution to this problem comes from the SelectString’s –Quiet switch. It simply returns True or False, depending on whether the file contains the string. So, to find the DLL in the current directory that contains the text "Debug":

GetChildItem | Where { $_ | SelectString "Debug" Quiet } Two other common tools used to search files for text are the –match operator and the switch statement with the –file option.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say