批处理文件在所有驱动器中搜索特定文件并将文件路径输出为变量

批处理文件在所有驱动器中搜索特定文件并将文件路径输出为变量

我正在尝试制作一个批处理程序来搜索特定文件,在本例中为“Apollo.exe”,我希望它搜索所有驱动器(包括 USB 驱动器)并将该文件的路径输出为变量,这样即使我不知道文件位置,我也可以启动文件“Apollo.exe”。到目前为止,我已经找到了这个,但它只搜索 C 盘。

@echo off
setlocal ENABLEDELAYEDEXPANSION
 
set filename=Apollo.exe

set searchPath=\

set foundFilePath= 

FOR /R "%searchPath%" %%a  in (%filename%) DO (
    IF EXIST "%%~fa" (
        echo "%%~fa" 
        SET foundFilePath=%%~fa
    )
)

IF EXIST "%foundFilePath%" (
    start "Apollo.exe" %foundFilePath%
    pause
) else (
    exit
)

答案1

这应该可以完成工作(根据需要修改):

@echo off
(
   for %%a in ( c d e f g h) do (
      if exist "%%a:\" dir "%%a:\Apollo.exe" /b /s /a-d
   )
)>"C:\Temp\list.txt"
set /P Variable=<"C:\Temp\list.txt"

如果需要更快的速度,您或许应该寻找一些第三方产品进行搜索。

答案2

定义变量而不创建/使用额外的文件......

@echo off 

for /f tokens^=1*delims^=: %%i in ('
fsutil fsinfo drives')do set "_drvs=%%~j"

for /f tokens^=*^delims^=? %%i in ('
call dir/b/a-d/s %_drvs:\=\Apollo.exe% 2^>nul 
')do set "_fpath=%%~dpi" && set "_file=%%~fi" && goto %:^)

%:^)
echo\Use "%_fpath%" and/or "%_file%"

其他资源:


答案3

我只是想添加另一种使用 wmic 来获取固定和可移动驱动器号的方法:


@echo off
Title Get Fixed And Removable Drives Letters
SETLOCAL EnableDelayedExpansion
set /a count=0
@for /f "tokens=2" %%i in ('wmic logicaldisk where "drivetype=2" 2^>nul ^|find /i ":" ') do (
    set /a count+=1
    Set "_USB_Drive[!Count!]=%%i"
)
::Show drive letter for removable drives if we found them
echo -----------------------------------------
echo Removable Drives found on this computer :
echo -----------------------------------------
@for /L %%i in (1,1,%count%) do (
    If Exist !_USB_Drive[%%i]! (
        echo %%i-!_USB_Drive[%%i]!\
        echo ------
    )
)
EndLocal
::Show drive letter for fixed drives
echo -----------------------------------------
echo Fixed Drives found on this computer :
echo -----------------------------------------
SETLOCAL EnableDelayedExpansion
set /a count=0
@for /f "tokens=2" %%i in ('wmic logicaldisk where "drivetype=3" 2^>nul ^|find /i ":" ') do (
    set /a count+=1
    Set "_Fixed_Drive[!Count!]=%%i"
)
::Show results for Fixed Drives
@for /L %%i in (1,1,%count%) do (
    If Exist !_Fixed_Drive[%%i]! (
        echo %%i-!_Fixed_Drive[%%i]!\
        echo ------
    )
)
EndLocal
pause

相关内容