'以管理员身份运行'时Windows批处理文件的起始目录

Mar*_*arc 71 windows directory uac batch-file windows-vista

我有一个批处理文件,它位于目录中,也必须从那里运行,因为它更新了该目录中的文件.
除非用户以管理员身份运行批处理文件(Vista上需要),否则此工作完全正常.然后起始目录是C:\ Windows\System32.

有没有办法仍然能够知道批处理文件从哪个目录运行?
我不希望用户手动输入目录.

Mar*_*tin 102

尝试访问批处理文件路径,如下所示:

echo %~dp0
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅for /?描述上述命令如何工作的命令的以下引用:

You can now use the following optional syntax:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path name
    %~dI        - expands %I to a drive letter only
    %~pI        - expands %I to a path only
    %~nI        - expands %I to a file name only
    %~xI        - expands %I to a file extension only
    %~sI        - expanded path contains short names only
    %~aI        - expands %I to file attributes of file
    %~tI        - expands %I to date/time of file
    %~zI        - expands %I to size of file
    %~$PATH:I   - searches the directories listed in the PATH
                   environment variable and expands %I to the
                   fully qualified name of the first one found.
                   If the environment variable name is not
                   defined or the file is not found by the
                   search, then this modifier expands to the
                   empty string

The modifiers can be combined to get compound results:

    %~dpI       - expands %I to a drive letter and path only
    %~nxI       - expands %I to a file name and extension only
    %~fsI       - expands %I to a full path name with short names only
    %~dp$PATH:I - searches the directories listed in the PATH
                   environment variable for %I and expands to the
                   drive letter and path of the first one found.
    %~ftzaI     - expands %I to a DIR like output line


Ben*_*oit 46

知足者常乐cd就是pushd这将

  • 如果从开始更改驱动器号 D:\...
  • 如果在UNC网络路径上,则分配驱动器号

所以pushd %~dp0很好.

好的做法就是popd在完成后打电话.

  • +1提及大多数未知的`pushd`命令. (3认同)

NMr*_*Mrt 26

这应该通过将批处理文件的工作目录设置回当前目录来解决您的问题:

在.bat脚本的顶部包含这两行:

@setlocal enableextensions
@cd /d "%~dp0"
Run Code Online (Sandbox Code Playgroud)

发现于:http://www.codeproject.com/Tips/119828/Running-a-bat-file-as-administrator-Correcting-cur

  • 太棒了。解决了以管理员身份运行 bat 文件时“找不到文件”的问题。 (3认同)

Maj*_*ush 5

要解决此问题,请在 .bat 脚本顶部包含以下两行:

@setlocal enableextensions
@cd /d "%~dp0"
Run Code Online (Sandbox Code Playgroud)