简体   繁体   中英

How to launch an exe file from a Batch file within an other batch file from different directories?

I will try to explain my problem :

  • I have a main batch file, named master.bat
  • I have several batch files, named slave_0x.bat called from master.bat with the CALL command.
  • Each slave_0x.bat file launch a setup_0x.exe file from a relative directory.
  • These two files are located in a sub-directory from the master.bat directory.

Per example :

  • master.bat file is located in D:\\Master\\
  • slave_01.bat is located in D:\\Master\\Slave_01\\
  • setup_01.exe is also located in D:\\Master\\Slave_01\\

The problem is :

When I launch master.bat, the current path is "D:\\Master\\" Then, when slave_01.bat is executed, it try to launch setup_01.exe from "D:\\Master\\" and not from "D:\\Master\\Slave\\"

REM Master.bat

@ECHO OFF
TITLE Installing Applications

SET mypath=%~dp0
ECHO %mypath:~0,-1%

ECHO.
ECHO 1) Installing App 1
ECHO.

call D:\Master\Slave_01\slave_01.bat"

ECHO.
ECHO 2) Installing App 2
ECHO.

CALL D:\Master\Slave_02\slave_02.bat"

PAUSE

slave_0x files :

REM slave_01.bat

TITLE App 1

ECHO.
ECHO %mypath:~0,-1%
ECHO.

ECHO Installing App 1
ECHO Please wait...

START /wait setup_01.exe /SILENT /SP- /NORESTART

Is there a way to use the current directory from the slave_0x.bat file instead the current directory from the master.bat file in the slave_0x.bat to launch the setup_0x.exe file from the right directory ?

Regards

To launch an executable that is in a different directory, add the relative path to the START command. Use %~dp0 to get the path of the currently running batch file.

START /wait %~dp0\setup_01.exe /SILENT /SP- /NORESTART

This launches the executable, but it doesn't change the process current directory.

If your executable relies on the current directory, then you will need to cd to that directory first. The easiest way to temporarily change directories is pushd and popd .

pushd %~dp0
START /wait setup_01.exe /SILENT /SP- /NORESTART
popd

Note : If the path or executable name can contain spaces, put the executable name in quotes as follows (including the mandatory dummy quotes)

START /wait "" "%~dp0\setup_01.exe" /SILENT /SP- /NORESTART

This is a common gotcha using the batch START command. See How to create batch file in Windows using "start" with a path and command with spaces

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