简体   繁体   中英

How to get the location of a file in a variable in a batch file?

Windows Command prompt Query: I have a root directory "A". There are several other sub-directories inside "A". Now somewhere inside these directories there is a file called "setup.exe". Now I want the complete path from A till the file. I will need this path later in my batch file. So I want it to be stored in some variable. I have found ways to get the path but not able to store it to some variable.

Kindly help.

Try this,it may help you.

for /r "C:\directory path" %%a in (*) do if "%%~nxa"=="setup.exe" set variable_to_store_path=%%~dpnxa
if defined variable_to_store_path (
echo %variable_to_store_path%
) else (
echo File not found
)

Let command DIR find setup.exe in directory tree and use command FOR to process the output of DIR to assign the found setup.exe with full path to an environment variable.

@echo off
set "SetupFile="
for /F "delims=" %%# in ('dir C:\a\setup.exe /A-D /B /S 2^>nul') do set "SetupFile=%%#"
if "%SetupFile%" == "" (
    echo Could not find setup.exe.
) else (
    echo Found %SetupFile%
)

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • echo /?
  • dir /?
  • for /?
  • if /?
  • set /?

See also Using command redirection operators to understand suppressing the error message of command DIR output to STDOUT on not finding any setup.exe by redirecting the error message to device NUL with 2>nul with escaping redirection operator > with ^ to be applied on execution of command DIR instead of producing a syntax error because a redirection specified within set / command / file specification of command FOR is not possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM