How to Find a File Recursively with PowerShell
Use Get-ChildItem to search a known directory tree instead of writing a recursive folder walker. Decide whether any match is enough or whether callers need a repeatable ordering.
Find the first enumerated match
$searchRoot = 'C:\Work\Downloads'
$match = Get-ChildItem -LiteralPath $searchRoot -File -Recurse -Filter '*download*' -ErrorAction Stop |
Select-Object -First 1
if ($null -eq $match) {
'No matching file found.'
} else {
$match.FullName
}
Replace the root with a real test directory and add a file such as daily-download.txt in a child directory. The command should print its full path. Remove or rename that test file and repeat against a tree with no matching names to exercise the empty result.
-File excludes directories. -Filter lets the filesystem provider apply the wildcard pattern during enumeration. The first result is an enumeration result, not necessarily the newest file or the alphabetically first path.
Make the selection reproducible
If alphabetical full-path order is the contract, collect and sort before selecting:
$match = Get-ChildItem -LiteralPath $searchRoot -File -Recurse -Filter '*download*' -ErrorAction Stop |
Sort-Object FullName |
Select-Object -First 1
This must enumerate the tree before it can choose the first sorted entry. For “newest,” sort by LastWriteTime descending instead and define a tie-breaker if ties matter.
Handle incomplete searches explicitly
A missing directory or an access-denied error should not silently become “not found.” This example stops on enumeration errors. If a best-effort inventory is appropriate, collect and report skipped paths separately.
Keep the search root narrow. Hidden files require an intentional -Force choice, and symbolic-link traversal requires a separate policy. Avoid recursively scanning every drive to answer a question about one application's directory.
References


Author: Herman Schoenfeld