如何在 Windows 批处理文件中设置命令的工作目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9597001/
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 09:19:47  来源:igfitidea点击:

How to set the working directory of a command in a Windows batch file?

windowsbatch-fileworking-directory

提问by Louis Rhys

Let's say I have these commands:

假设我有这些命令:

Prog1.exe
D:\SomeDir\Prog2.exe
Prog3.exe

Now, say for the second line, I would like the working directory to be D:\SomeDir, but in Prog1.exe and Prog3.exe I want the default working directory (normally, where my .bat file is). If I try this

现在,对于第二行,我希望工作目录为 D:\SomeDir,但在 Prog1.exe 和 Prog3.exe 中,我想要默认工作目录(通常,我的 .bat 文件所在的位置)。如果我试试这个

Prog1.exe
cd D:\SomeDir
D:\SomeDir\Prog2.exe
Prog3.exe

Apparently Prog3 will be executed in SomeDir, which is not what I want.

显然 Prog3 将在 SomeDir 中执行,这不是我想要的。

回答by jeb

You could use the pushd/popd commands (help with pushd /?)

您可以使用 pushd/popd 命令(帮助pushd /?

Prog1.exe
Pushd D:\SomeDir
Prog2.exe
popd
Prog3.exe

回答by David Ruhmann

You could use the cd command (help with cd /?) with the %~dp0, batch file path, variable.

您可以将 cd 命令(帮助cd /?)与%~dp0, 批处理文件路径,变量一起使用。

Prog1.exe
cd D:\SomeDir
Prog2.exe
cd %~dp0
Prog3.exe

For a complete list of %~modifiers see call /?or for /?help.

有关%~修饰符的完整列表,请参阅call /?for /?帮助。

However, I only add this as to provide a more complete answer on Stack Overflow. I would RECOMMEND using jeb's solution above.

但是,我添加这个只是为了在 Stack Overflow 上提供更完整的答案。我会推荐使用上面 jeb 的解决方案。

回答by Ryan

What worked for me is adding a /d:

对我有用的是添加一个/d

cd /d C:\nginx
ECHO Stopping nginx...
start nginx -s quit

(When I didn't have the /d, it didn't work.)

(当我没有 时/d,它不起作用。)

https://stackoverflow.com/a/18310141/470749tries to explain it.

https://stackoverflow.com/a/18310141/470749试图解释它。