3

Pseudo code:

path = ".";
for(;;)
{
   if(exist(path + "/file.exe")
       break;
   path += "/..";
}

basically, I have a script that is run from a folder that is a few levels deep from the folder that contains file.exe and I need to find what the path is of that folder.

For a quick workaround, I added this to my bat file:

set PATH=..;..\..;..\..\..;..\..\..\..;%PATH%

is there a proper way to iterate folders and check if a file exist in them?

Pavel P
  • 15,789
  • 11
  • 79
  • 128

3 Answers3

3

You can capture the output of DOS commands using the "usebackq" keyword and enclosing the command string in ` characters. You can then use the DOS dir command with the bare output (/B) and subdirectory search (/S) switches along with your desired filename to produce a fully qualified path string to that filename. In this example, i have testFile.exe in test/test2 in my current directory.

in test.bat:

@FOR /F "usebackq" %%y in (`dir /s /b testFile.exe`) do @echo Filename: %%y

my output:

Filename: C:\TEST_REMOVE\test\test2\testFile.exe

hope it helps!

_ryan

ryan0
  • 1,482
  • 16
  • 21
  • I got the idea, although I need to do it in opposite order. The testFile.exe is located in TEST_REMOVE and current dir is located somewhere inside test/test2 or maybe a few more level deep and I need to go up to find location of the testFile.exe – Pavel P Aug 22 '12 at 21:44
  • sorry, i misread the question. this method is no longer elegant; you should go with Harry's solution. – ryan0 Aug 23 '12 at 01:37
3

I would try something like

pushd
:loop
if exist file.exe goto :found
set lastdir=%cd%
cd ..
if "%cd%" EQU "%lastdir%" goto :notfound
goto :loop
:notfound
echo file.exe not found!
popd
goto :eof
:found
set file=%cd%\file.exe
popd
Harry Johnston
  • 35,639
  • 6
  • 68
  • 158
0

here is a site you can look at that will give you examples on how and where to start

How to create a batchfile to read all files in a directory

I would also suggest doing a Google Search- That's what I did to get this link

Community
  • 1
  • 1
MethodMan
  • 18,625
  • 6
  • 34
  • 52