batch file to search all drives for a specific file and output the file path as a variable

i am trying to make a batch program that will search of a specific file, in this case "Apollo.exe" i want it to search all drives including USB drives and output the path of said file as a variable so that i can start the file "Apollo.exe" even if i dont know the file location. I have found this so far but it only searches C drive.

@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
)

This should do the job (modify as required):

@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"

If more speed is required, you should perhaps look for some third-party product for searching.


Defining your variable without creating/using additional file...

@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%"

Additional Resources:

  • Set /?
  • Echo /?
  • Fsutil /?
  • For /?
  • For /F /?
  • Redirection
    • |, <, >, 2>, etc.
  • Conditional Execution
    • || and &&
  • Goto :Label | Call :Label
  • Variable and Substring Manipulation
  • How does the Windows Command Interpreter [cmd.exe] Parse Scripts


Just i want to add another way using wmic to get fixed and removable drives letters :


@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