Command line .cmd/.bat script, how to get directory of running script

后端 未结 3 1052
北海茫月
北海茫月 2021-01-30 15:26

How can you get the directory of the script that was run and use it within the .cmd file?

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-30 16:27

    This is equivalent to the path of the script:

    %~dp0
    

    This uses the batch parameter extension syntax. Parameter 0 is always the script itself.

    If your script is stored at C:\example\script.bat, then %~dp0 evaluates to C:\example\.

    ss64.com has more information about the parameter extension syntax. Here is the relevant excerpt:

    You can get the value of any parameter using a % followed by it's numerical position on the command line.

    [...]

    When a parameter is used to supply a filename then the following extended syntax can be applied:

    [...]

    %~d1 Expand %1 to a Drive letter only - C:

    [...]

    %~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which may be interpreted as an escape character by some commands.

    [...]

    The modifiers above can be combined:

    %~dp1 Expand %1 to a drive letter and path only

    [...]

    You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script e.g. W:\scripts\

提交回复
热议问题