简单的Windows批处理移动文件夹方法

3

我只是想把 d:\temp\test 内所有的文件和子目录移动到 d:\temp\archive,所以我尝试了以下命令:

move d:\temp\test\* d:\temp\archive\
move d:\temp\test\*.* d:\temp\archive\

但是我收到了以下错误信息:
The filename, directory name, or volume label syntax is incorrect.

然后我在网上搜索并尝试在doc批处理文件中输入以下内容:

for %%F in ( d:\temp\test\*.* ) do move /Y %%F d:\temp\archive

这一次没有出现错误,但是一切都静止不动,没有任何改变。

我错过了什么?我正在尝试在Windows 10上运行此操作。

1个回答

4

好的,如果您只想移动\test目录中的所有文件夹和文件,那么以下命令将先复制所有文件,然后按批复制所有文件夹。for /d会复制文件夹、子文件夹和文件。

@echo off
move "d:\temp\test\*" "d:\temp\archive"
for /d %%a in ("D:\temp\test\*") do move "%%~fa" "d:\temp\archive\"

作为一则附注,从 cmd 运行以下命令时会出现错误。
move d:\temp\test\* d:\temp\archive

那是因为它会移动所有文件,但不包括目录。如果你得到了“文件名、目录名或卷标语法不正确”的提示,那么就只有文件夹而没有文件,你的移动命令看不到它们。
注意,在批处理文件中,“/Y”开关被禁用,如果存在文件夹,则不会替换文件夹。因此,如果您计划经常覆盖,请使用“xcopy”并更新存档,然后在文件成功复制后运行“d:\temp”中的删除操作。
最后,请始终将路径用双引号括起来。在这种情况下,它可以很好地工作,没有双引号也没问题,但如果您有像“move d:\program files\temp\* d:\temp\archives”这样的东西,它将因为program和files之间的空格而出错,因此最好使用“move"d:\program files\temp\*" "d:\temp\archive"”。
编辑:理解“%%~”分配。在这些示例中,我们使用“%%I”代替“%%a”。
%~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`

谢谢!您能解释一下"%%~fa"是什么意思吗?我只知道"%%a"代表"d:\temp\test"里的每个文件夹。 - jimzcc
1
当然。%%~fa代表完全限定的路径。请记住,我们将%%a分配给 D:\temp\test\*,其中*是完整路径,因此 %%~fa 是完整路径。因此,如果您有 D:\temp\test\folder1D:\temp\test\folder2,每个文件夹都会成为 %%~fa,为了查看其运作原理,请创建一个批处理并插入以下内容。它将只回显完整路径。 @echo off for /d %%a in ("D:\temp\test\*") do echo %%~fa - Gerhard
那么你的意思是,“%%fa”和“%%na”比“%%a”更安全? - jimzcc

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