从批处理文件所在的目录复制文件

10

我只了解批处理文件的基础知识。 我正在尝试编写一个批处理文件,它可以在任何目录中复制同一目录中的文件并将其放置在新位置。 我知道如何复制和移动文件,但不知道如何编写批处理文件以理解其目录,然后获取另一个文件。

我读到%0代表文件所在的目录,但是如何将文件附加到其中呢?

我尝试过这个:

copy "%0\Move.txt" "C:\"

也许那很蠢,但我是新手。请帮帮我?

2个回答

22

%0 包含批处理脚本的完整路径和文件名。

只需使用 %~dp0 即可获取不带批处理脚本文件名的路径。

copy "%~dp0\Move.txt" "C:\"

当您遇到问题时,使用echo命令来查看变量所包含的内容。

echo %0

call /?

Substitution of batch parameters (%n) has been enhanced.  You can
now use the following optional syntax:

    %~1         - expands %1 removing any surrounding quotes (")
    %~f1        - expands %1 to a fully qualified path name
    %~d1        - expands %1 to a drive letter only
    %~p1        - expands %1 to a path only
    %~n1        - expands %1 to a file name only
    %~x1        - expands %1 to a file extension only
    %~s1        - expanded path contains short names only
    %~a1        - expands %1 to file attributes
    %~t1        - expands %1 to date/time of file
    %~z1        - expands %1 to size of file
    %~$PATH:1   - searches the directories listed in the PATH
                   environment variable and expands %1 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:

    %~dp1       - expands %1 to a drive letter and path only
    %~nx1       - expands %1 to a file name and extension only
    %~dp$PATH:1 - searches the directories listed in the PATH
                   environment variable for %1 and expands to the
                   drive letter and path of the first one found.
    %~ftza1     - expands %1 to a DIR like output line

In the above examples %1 and PATH can be replaced by other
valid values.  The %~ syntax is terminated by a valid argument
number.  The %~ modifiers may not be used with %*

我很感激。但是,如果我键入echo %0,它只会返回%0? - Kyle Wright
1
@KyleWright %0 表示批处理文件内可用的参数0。 直接在命令行上使用 echo %0 无效。 - David Ruhmann

2

如果您只是想将当前目录中的文件复制到新目录中,可以简单地执行以下操作:

copy "Move.txt" "C:\"

没有在文件“Move.txt”前加前缀意味着它位于当前目录中。

4
如果批处理脚本在不同的工作目录下通过命令行运行,就会出现问题。这就是为什么如果没有执行cd或者pushd,通常会使用%0的原因。请注意,此处只是翻译,不包含解释或其他内容。 - David Ruhmann
1
啊,我误解了问题。谢谢。 - gh123man

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接