How to execute programs in the same directory as the windows batch file?
Asked Answered
A

3

95

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?

Adactylous answered 28/4, 2010 at 15:2 Comment(1)
FYI: you couldn’t run a.cmd or .\\a.cmd because the current working directory of the shell was not the batch file’s directory.Mark
S
193

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 \.

Spina answered 28/4, 2010 at 15:10 Comment(3)
+1 vote just found this link on google search - weblogs.asp.net/whaggard/archive/2005/01/28/…Sculptor
Patrick 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"Brandwein
To 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 thatVasta
F
35

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
Faitour answered 5/4, 2016 at 9:39 Comment(2)
Note 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 thatCinelli
This code works best! I would add set workpath=%cd% before pushd %~dp0 to keep a reference to the working path which then can be passed to the .exe if needed like that ProgramInSameFolderAsBat.exe -workingpath "%workpath%" %*Sahib
I
0

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

Infrequent answered 17/12, 2022 at 14:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.