2012-08-22 95 views
3

僞代碼:Windows批處理FOR循環找到一個文件夾

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

基本上,我有一個從深幾級從包含的file.exe,我需要的文件夾的文件夾運行腳本找到該文件夾​​的路徑。

對於一個快速的解決辦法,我已將此添加到我的BAT文件:

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

有遍歷文件夾,並檢查文件是否在其中存在一個適當的方式?

回答

3

我會嘗試像

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 
3

您可以使用「usebackq」關鍵字捕獲DOS命令的輸出,並將命令字符串包含在「characters」中。然後,您可以使用帶有裸輸出(/ B)和子目錄搜索(/ S)開關的DOS dir命令以及所需的文件名來生成該文件名的完全限定路徑字符串。在這個例子中,我在我當前目錄中的test/test2中有testFile.exe。

在test.bat的:

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

我的輸出:

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

希望它能幫助!

_ryan

+0

我上心,但我需要做的是相反的順序。 testFile.exe位於TEST_REMOVE中,當前目錄位於test/test2內部或者更深層次,我需要去查找testFile.exe的位置。 – Pavel

+0

對不起,我誤解了這個問題。這種方法不再優雅;你應該和Harry的解決方案一起去。 – ryan0