windows %CD% 变量行为在右键单击并以管理员身份运行时有所不同

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

%CD% variable behaviour differs when right click and use run as admin

windowsbatch-filecmd

提问by Pedro Santos

I have a windows cmd file that is making use of the %CD% environment variable to determine the execution directory of the cmd file.

我有一个 Windows cmd 文件,它使用 %CD% 环境变量来确定 cmd 文件的执行目录。

When I run the cmd file from the command line it works correctly, meaning that the %CD% variable contains the working directory. If I double left click the cmd it also works as I expect. However if I right click the cmd file and select runas administrator then the %CD% variable contains the value "C:\Windows\system32" not the curent directory where the cmd is executing.

当我从命令行运行 cmd 文件时,它可以正常工作,这意味着 %CD% 变量包含工作目录。如果我左键双击 cmd,它也可以按我的预期工作。但是,如果我右键单击 cmd 文件并选择 runas administrator,则 %CD% 变量包含值“C:\Windows\system32”,而不是执行 cmd 的当前目录。

I was able to reproduce the problem with the following script:

我能够使用以下脚本重现该问题:

echo %CD%
pause

回答by ewall

Trying using %~dp0instead of %cd%... this should give you the directory which contains the batch (NT shell) script was launched from in any case.

尝试使用%~dp0而不是%cd%......这应该会给你包含在任何情况下启动的批处理(NT shell)脚本的目录。

回答by Anders

Are you confusing working/current directory with the directory your batch file is in?

您是否将工作/当前目录与批处理文件所在的目录混淆了?

If I have a simple batch file with just

如果我有一个简单的批处理文件

@echo off
echo %cd%

and this is stored in c:\foo\bar\test.cmd

这存储在 c:\foo\bar\test.cmd

In cmd I execute

在 cmd 我执行

cd c:\foo
bar\test

test.cmd will print c:\fooand not c:\foo\bar

test.cmd 将打印c:\foo而不是c:\foo\bar

I assume UAC uses system32 since it is possible to elevate with a different user and that user might not have access to whatever the current directory is.

我假设 UAC 使用 system32,因为可以使用不同的用户进行提升,并且该用户可能无法访问当前目录的任何内容。

If you want the directory your batch file is in, use %~dp0, if you want the current directory, use . or %CD%

如果您想要批处理文件所在的目录,请使用 %~dp0,如果您想要当前目录,请使用 . 或 %CD%