93

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?

Jader Dias
  • 88,211
  • 155
  • 421
  • 625

3 Answers3

190

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

Patrick Cuff
  • 28,540
  • 12
  • 67
  • 94
  • 2
    +1 vote just found this link on google search - http://weblogs.asp.net/whaggard/archive/2005/01/28/get-directory-path-of-an-executing-batch-file.aspx – house9 Apr 28 '10 at 15:17
  • 29
    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" – Stephen C Feb 05 '13 at 17:50
  • Thank you, been searching for this answer for a while, nothing was as efficient or fitted to my problem! – MD XF Sep 30 '16 at 21:08
  • 2
    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 that – Thomas Mulder Jan 04 '17 at 12:19
  • Thanks a lot for the explanation. – Tarek Apr 01 '19 at 12:57
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
Bruno
  • 1,213
  • 13
  • 14
  • 1
    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 that – Bilal Akil Dec 23 '19 at 05:22
  • 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%" %*` – Dimitar Atanasov Feb 22 '22 at 15:47
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

Kyo
  • 61
  • 6