xcopy - 复制至少一个匹配模式的文件
xcopy - copy at least one file matching a pattern
每当 xcopy
找不到文件时,它会将 errorLevel
变量从 0
更改为其他内容。
在我们公司,我们有使用 xcopy
复制文件并根据此 errorLevel
.
执行操作的大型脚本
它对特定文件或目录绝对有效。
工作得很好:
xcopy file dir
if %errorlevel% neq 0 exit -1
但是,如果我想使用 *
而不是指定文件的确切名称,那么检查 errorLevel
将不再有效。
无效:
xcopy file* dir
if %errorlevel% neq 0 exit -1
我会得到:
File not found - file*
0 File(s) copied
但是 errorLevel
会是 0
。
如何确保在使用通配符时至少复制了 1 个文件?
xcopy
命令在使用通配符时,不会将零个匹配文件视为错误。
作为一种变通方法,您可以使用 where
命令检查是否至少有一个匹配项目,在这种情况下它会将 ErrorLevel
设置为 0
,但要 1
否则。添加开关 /Q
可防止 where
输出任何内容并使其仅 return ErrorLevel
:
where /Q "file*"
if %errorlevel% neq 0 exit -1
xcopy "file*" "dir"
if %errorlevel% neq 0 exit -1
您不能对 ErrorLevel
进行一次检查,因为 xcopy
会覆盖 where
的 ErrorLevel
。但是,您可以像这样缩短上面的内容:
where /Q "file*" || exit -1
xcopy "file*" "dir" || exit -1
甚至像这样:
where /Q "file*" && xcopy "file*" "dir" || exit -1
我在这里将所有文件和目录规范放在引号之间,因为如果其中任何一个包含空格,这是唯一安全的方法。
每当 xcopy
找不到文件时,它会将 errorLevel
变量从 0
更改为其他内容。
在我们公司,我们有使用 xcopy
复制文件并根据此 errorLevel
.
它对特定文件或目录绝对有效。
工作得很好:
xcopy file dir
if %errorlevel% neq 0 exit -1
但是,如果我想使用 *
而不是指定文件的确切名称,那么检查 errorLevel
将不再有效。
无效:
xcopy file* dir
if %errorlevel% neq 0 exit -1
我会得到:
File not found - file*
0 File(s) copied
但是 errorLevel
会是 0
。
如何确保在使用通配符时至少复制了 1 个文件?
xcopy
命令在使用通配符时,不会将零个匹配文件视为错误。
作为一种变通方法,您可以使用 where
命令检查是否至少有一个匹配项目,在这种情况下它会将 ErrorLevel
设置为 0
,但要 1
否则。添加开关 /Q
可防止 where
输出任何内容并使其仅 return ErrorLevel
:
where /Q "file*"
if %errorlevel% neq 0 exit -1
xcopy "file*" "dir"
if %errorlevel% neq 0 exit -1
您不能对 ErrorLevel
进行一次检查,因为 xcopy
会覆盖 where
的 ErrorLevel
。但是,您可以像这样缩短上面的内容:
where /Q "file*" || exit -1
xcopy "file*" "dir" || exit -1
甚至像这样:
where /Q "file*" && xcopy "file*" "dir" || exit -1
我在这里将所有文件和目录规范放在引号之间,因为如果其中任何一个包含空格,这是唯一安全的方法。