Powershell

How to Search a String in Multiple Files and Return the Names of Files in PowerShell

PowerShell is a Windows utility that allows you to search for the strings in multiple files. Additionally, it returns the file names which contain the corresponding string. PowerShell uses “select-string” and “sls” cmdlets to search strings in multiple files. More specifically, “select-string” is equivalent to the “grep” command of Linux, which is used for finding text patterns in the files.

This post will demonstrate various methods to search a string in multiple files.

How to Search a String in Files and Get the Names of Files Back in PowerShell?

These enlisted methods can be used to search a string in multiple files:

Method 1: Search a String in Multiple Files and Return File Names Using “select-string” Cmdlet

The string can be searched in multiple files using the “select-string” cmdlet. This cmdlet selects the strings and searches for text patterns in multiple files as follows:

> Get-Childitem C:\Doc -recurse | select-string -pattern "LinuxHint"

Here:

  • Get-ChildItem” cmdlet is used to fetch the file from the specified location.
  • -recurse” flag forces the search to find the matching string in the sub-folders.
  • |” pipe operator is utilize to send the command’s output as the input of the next command.
  • -pattern” flag defines the specific string to be searched.

Output

The given output indicates that according to the specified pattern, the matched string with the relevant file names has been returned.

Method 2: Search a String in Multiple Files and Return File Names Using “sls” Cmdlet

sls” is an alias of the “select-string” cmdlet and also works the same. The “sls” command is used with the “ls” cmdlet.

We have provided an example to demonstrate the working of the “sls” cmdlet to search a string in multiple files:

> ls C:\Doc -r | sls "LinuxHint"

Here:

  • ls” cmdlet is used to list the files and folders.
  • -r” is the alias of the “-recurse” cmdlet used to force the search to find the string in sub-folders:

It can be observed that file names with the specified string have been fetched successfully.

Conclusion

To search a string in multiple files in PowerShell, use the “select-string” or the “sls” cmdlets. In the first method, use the “select-string” with the “Get-ChildItem” cmdlet, “-recurse” and “-pattern” flags, and pipeline (|) that joins the output of one command to the input of the other. In the “sls” command, use all the aliases of the commands used in the first approach. Because “sls” is the alias of the “select-string” cmdlet. This post has presented several methods for searching a string in multiple files.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.