meue
meue

Reputation: 148

Search directory for a file, iterating up parent directories if not found

Given:

$path = c:\dir1\dir2\dir3\dir4\dir5

I want to search for var.txt starting in the lowest child directory (dir5).

If var.txt is there, do something, if not, search the next level (in this case dir4) for var.txt and repeat.

Possibly relevant links:

How I could use test-path to check for var.txt

Recursion, maybe?

Ideas:

Somehow using Split-Path, in a loop which iterates -Parent, and using test-path each iteration to check for var.txt


Solution:

Incorporating the solution below with actions, and breaking the loop if not found at the highest directory:

$file = ""
$path = ""
while($path -and !(Test-Path (Join-Path $path $file))){
    if($path -eq ((Split-Path -Path $path -Qualifier)+"\")){
        break
    }
    else {
        $path = Split-Path $path -Parent
    }
}
if($path -ne ((Split-Path -Path $path -Qualifier)+"\")){
    #do something
}

Upvotes: 3

Views: 1386

Answers (2)

Esperento57
Esperento57

Reputation: 17492

Try this (recursive method) :

function GetPathIfFileExist($pathtosearch, $filename)
{
   if($pathtosearch -eq "")
   {
       "file not founded"
   }
   elseif (Test-Path "$pathtosearch\$filename" )
   {
       $pathtosearch
   }
   else
   {
      GetPathIfFileExist (Split-Path $pathtosearch) $filename
   }
}

GetPathIfFileExist "c:\dir1\dir2\dir3\dir4\dir5" "var.txt"

Upvotes: 5

E.V.I.L.
E.V.I.L.

Reputation: 2166

$path = 'c:\dir1\dir2\dir3\dir4\dir5'
while($path -and !(Test-Path (Join-Path $path 'var.txt'))){
    $path = Split-Path $path -Parent
}
Write-Output (Join-Path $path 'var.txt')

Assumes that var.txt exists in one of those dirs, and that you know the path.

Upvotes: 4

Related Questions