PowerShell: how to recursively Test-Path up the directory tree?

Viewed 688

I can't seem to figure out how to climb up the directory and check each parent folder for an item. I.e., from where ever get-location is, I'd like to check (get-location).parent, and then check (get-location).parent.parent and etc. until I get back to the root, c:.

Here's what I've figured out so far, but it seems cumbersome and unwieldy. I get that to see if it exists, I should use something like:

test-path (get-item $t).Parent.Parent

but that won't climb up the directory tree like I want, and I can't grok how to get it to work in combination with Split-Path...

I thought something like:

$p = split-path $(get-location) -Parent
if ( (split-path $p -leaf) -eq "test" ) {
    $q = $(Split-Path $p -parent ) 
} elseif ( (split-path $q -leaf) -eq "test") {
    $r = (split-path $q -leaf) -eq "test"
}

might work, but it's not as recursive as I'd like it to be.

1 Answers
# The name of the file to look for.
$fileName = 'somefile.txt'

# Where to start looking (the current dir).
$dir = $PWD.ProviderPath

# Walk up the directory hierarchy until the first file whose name
# matches $fileName is found, and return that file's path.
# If no such file is found, $file is (effectively) $null.
$file = 
 do { 
   if (Test-Path -Type Leaf -LiteralPath ($file = "$dir/$fileName")) { 
     $file # output the path of the file found.
     break # exit the loop
   }
 } while ($dir = Split-Path -LiteralPath $dir)
Related