windows 如何在与windows批处理文件相同的目录中执行程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2730643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:17:44  来源:igfitidea点击:

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

windowsbatch-filepathrelative-path

提问by Jader Dias

I have in the same folder a .batand a .exefile. I couldn't call the .exefile from the .batunless I put the full absolute path to it. Is there a way to don't specify the path?

我在同.bat一个.exe文件夹中有一个文件。除非我将完整的绝对路径放入其中.exe.bat否则我无法调用该文件。有没有办法不指定路径?

回答by Patrick Cuff

Try calling the .exewith %~dp0, like this: %~dp0MyProgram.exe.

尝试调用.exe%~dp0,像这样:%~dp0MyProgram.exe

%0contains the full path to the called .batfile.

%0包含被调用.bat文件的完整路径。

~dpsays to get the drive and path, including trailing \.

~dp说要获取驱动器和路径,包括尾随\

回答by Bruno

I solved this by changing the working directory using pushdat 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更改工作目录并在脚本末尾使用popd 进行恢复来解决此问题。这样您就可以始终假设工作目录与 bat 文件的位置相同。

pushd %~dp0
ProgramInSameFolderAsBat.exe
popd