'How do I search recursively in directories above a path in DOS?

I have a directory path and I want to find a particular file in a directory directly above my path. Similar to the MSBuild command

"$([MSBuild]::GetPathOfFileAbove(filename.ext))"

except in a DOS prompt.

So if my directory path is c:\one\two\three\four I want to look for filename.ext in c:\one\two\three\four, then in c:\one\two\three, then in c:\one\two, then in c:\one, then in c:, and return the path to the first instance of filename.ext I find. Is that possible in a simple DOS script?

The FOR command only seems to have /r, for searching recursively below the supplied directory path. I've searched everything I can think of and only found solutions for searching subdirectories below a path.



Solution 1:[1]

There is no such command. (I doubt, there is one in any language). So you need to climb up the tree by yourself.

Look if the file is in the current folder. If it is, store the folder and break the loop. Else go up one step and loop until you are on the top.

@echo off 
:loop
echo ---- current = %cd%
dir /b desired.txt >nul 2>&1 && (set "folder=%cd%" & goto :finish)
if "%cd:~3%" == "" goto :finish
cd..
goto :loop
:finish
echo found file in %folder%

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1