I have in the same folder a .bat and a .exe file.
I couldn't call the .exe file from the .bat unless I put the full absolute path to it.
Is there a way to don't specify the path?
3 Answers
Try calling the .exe with %~dp0, like this: %~dp0MyProgram.exe.
%0 contains the full path to the called .bat file.
~dp says to get the drive and path, including trailing \.
-
2+1 vote just found this link on google search - weblogs.asp.net/whaggard/archive/2005/01/28/…– house9Apr 28, 2010 at 15:17
-
32Patrick Cuff's answer above works, but fails if part of the directory path has spaces in its name. To get around this you need to put double quotes around the .exe call. "%~dp0MyProgram.exe" Feb 5, 2013 at 17:50
-
2To add to this answer, if you change your execution path to the current directory as follows:
cd "%~dp0"you can just call MyProgram.exe just like that Jan 4, 2017 at 12:19
I solved this by changing the working directory using pushd at the start of the script and restoring is at the end of the script using popd. This way you can always assume the working directory is the same as the location of the bat file.
pushd %~dp0
ProgramInSameFolderAsBat.exe
popd
-
1Note that changing working directory could have side-effects within the executed file/script. In my case, I needed the working directory to remain as it was. @Patrick Cuff's answer worked in consideration of that Dec 23, 2019 at 5:22
-
This code works best! I would add
set workpath=%cd%beforepushd %~dp0to keep a reference to the working path which then can be passed to the .exe if needed like thatProgramInSameFolderAsBat.exe -workingpath "%workpath%" %*Feb 22, 2022 at 15:47
As Stephen C said, to properly support paths with spaces we can use:
start "%~dp0" "myfile.exe"
or with arguments:
start "%~dp0" "myfile.exe" -my_arguments
a.cmdor.\\a.cmdbecause the current working directory of the shell was not the batch file’s directory.