This post will explain a complete guide to searching files using PowerShell.
How to Search a File Using Recursive Search in PowerShell?
These are the methods that can be used to search recursively through files in PowerShell:
Method 1: Search a File Using Recursive Search in PowerShell Using “Get-ChildItem” Cmdlet
“Get-ChildItem” is a specific command on PowerShell that is used to look for the files and folders in the provided location. Moreover, it does not show the empty folders from the specified path when a “-Recurse” flag is used. This flag is used to search recursively through the sub-folders.
Example 1: How to Search a File with a Specific Name in Different Directories?
In this example, we will use the “Get-ChildItem” with “-Filter” and “-Recurse” flags to search a single file with a filename as follows:
Here:
- “-Filter” flag is used to find the exact file as specified in the command.
- “-Recurse” flag forces the command to search the file in the sub-folders:
Example 2: How to Search Files with a Specific Extension?
You can also utilize the same command to search files by providing the specific extension. For that reason, use the “Get-ChildItem” cmdlet, add the folder path, write the file extension with a “wild character *”, such as “*.txt”, and finally add the “-Recurse” parameter at the end.
Here, the “wild character *” is used to locate the file with the specific extensions in the specified directory:
Method 2: Search a File Using Recursive Search in PowerShell Using “Dir ” Cmdlet
Another cmdlet that can be used to search recursively using PowerShell is the “Dir”. It is basically the alias of the “Get-ChildItem” cmdlet used to display the files and folders from the specified directory.
Example 1: How to Search a File with a Specific Name in Different Directories?
To search a single file with a specific name, first, add the “Dir” cmdlet, add the file path, specify the “-Filter” flag, write the exact file name with its extension and finally add the “-Recurse” flag:
Example 2: How to Search Files with a Specific Extension?
Files with a specific extension can be searched recursively using the given command. Only add the file extension with “wild character *” at the start, such as “*.txt”:
The output shows that the files with specific extensions have been searched recursively from the given directory.
Conclusion
Files on Windows can be searched recursively using the “Get-ChildItem” cmdlet with the combination of the “-Recurse” flag. To find a file with the file name “-Filter” flag is used. Moreover, to search files with specification extension, just add the extension with the “wild character *” at the start, just like that “*.txt”. This post has provided a complete procedure to search the files recursively using PowerShell.