Find File Recursively in Powershell

Hey PowerShell fans,

Today I want to share with you a handy function that I use all the time to find files by name in any folder or subfolder. It’s called rsf, which stands for recursive search file.

The function takes one argument, which is the name or pattern of the file you are looking for. For example, if you want to find all the .txt files in your current directory and its subdirectories, you can simply type rsf *.txt

The function uses the Get-ChildItem cmdlet with the -Include and -File parameters to filter only files that match the given argument. It also uses the -Recurse parameter to search in all subfolders.

f you want to find a file with a specific name in a folder or its subfolders, you can use PowerShell to do it easily. To recursively search for a file named cmake.exe, you can use this command:

Get-ChildItem -Include cmake.exe -File -Recurse

This will list all the files that match the name cmake.exe in the current folder and any subfolders. You can also use a wildcard mask to filter by part of the name or extension. For example, if you want to find all the files that start with cmake and have any extension, you can use this command:

 Get-ChildItem -Include *cmake* -File -Recurse

Or if you want to find all the files that have cmake in their name and have three letters after the dot, you can use this command:

Get-ChildItem -Include cmake.??? -File -Recurse

Sample output:

alone@isb C:\ ❯❯❯ Get-ChildItem -Include cmake.exe -File -Recurse

    Directory: C:\dev\vcpkg\downloads\tools\cmake-3.24.0-windows\cmake-3.24.0-windows-i386\bin

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          04/08/2022    15:09        8807048 cmake.exe

    Directory: C:\Program Files\Microsoft Visual
Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          25/08/2022    17:59       10621376 cmake.exe

You can add this function to your profile.ps1 file so that it is always available when you open a PowerShell session. Just wrap it in a function and add to profile:

function rsf($arg) {
     Get-ChildItem -Include $arg -File -Recurse
}

To use the function, just type rsf followed by the name or extension of the file you are looking for. For example, rsf *.txt will find all text files in your current directory and subdirectories. You can also use wildcards in the argument, such as rsf report*.docx to find all Word documents that start with report.

Happy scripting!


To contact me, send an email anytime or leave a comment below.