在批处理脚本中设置for循环

我正在尝试创build一个batch file扫描文件夹的文件

for /RD:\path\import_orders\xml_files\ %%f in (*.xml) do( copy %%f "\\destination" if errorlevel 0 move %%f "D:\path\import_orders\xml_files\archive\" ) 

固定但它不会工作。 如果我执行它,它只打印第一行代码它现在有效。 我在“do(”之后加了一个空格,现在执行了。

1)是我的第二个命令好吗? 如果第一个命令一切顺利,我想将复制的文件移动到归档中。

2)我应该如何改变循环工作只在给定的目录中的文件,而不是在其中的子目录?

  • 您错过了do和括号之间的空格

  • if errorlevel n的计算结果为true,那么任何错误级别的值都等于或大于n,那么if errorlevel 0对于任何非负的错误级别值都为真。 你应该使用, if not errorlevel 1

  • 引用所有路径是一个好习惯,以防万一包含空格或特殊字符

 for /R "D:\path\import_orders\xml_files" %%f in (*.xml) do ( copy "%%~ff" "\\destination" if not errorlevel 1 move "%%~ff" "D:\path\import_orders\xml_files\archive\" ) 

为了避免目录递归,只需更改for循环,删除/R (要求递归)将开始文件夹的提示移动到文件选择模式。

 for %%f in ("D:\path\import_orders\xml_files\*.xml") do ( copy "%%~ff" "\\destination" if not errorlevel 1 move "%%~ff" "D:\path\import_orders\xml_files\archive\" ) 

但是在任何情况下,如果目标文件存在, copy命令不要求确认。 如果你不想覆盖现有的文件,你有一些选择

使用copy命令的开关

你可以使用/-y所以copy命令会覆盖文件之前要求确认,并自动化过程,你可以通过管道答案的问题

 echo n|copy /-y "source" "target" 

这是npocmaka答案中的方法 。 这种方法应该没有问题,但是

  • 有两个需要创建两个cmd实例来处理管道的每一侧,并为每个源文件执行,所以它会减慢进程

  • 如果代码在覆盖问题没有等待N字符的地区执行,否则可能会失败。

首先检查文件的存在

if exist构造, if exist可以使用内建来首先检查目标文件是否存在

 if not exist "\\destination\%%~nxf" copy "%%~ff" "\\destination" 

其中%%~nxf表示正在处理的文件的名称和扩展名

所以,最终的代码可能是

 for %%f in ("D:\path\import_orders\xml_files\*.xml") do ( if not exist "\\destination\%%~nxf" copy "%%~ff" "\\destination" if not errorlevel 1 move "%%~ff" "D:\path\import_orders\xml_files\archive\" ) 
 for /R "D:\path\import_orders\xml_files\" %%f in (*.xml) do ( (echo n|copy /-y "%%~ff" "\\destination"|find /i "0 file(s) copied." >nul 2>&1)||( move "%%~ff" "D:\path\import_orders\xml_files\archive\" ) ) 

编辑而不搜索子目录:

 for %%f in ("D:\path\import_orders\xml_files\*.xml") do ( (echo n|copy /-y "%%~ff" "\\destination"|find /i "0 file(s) copied." >nul 2>&1)||( move "%%~ff" "D:\path\import_orders\xml_files\archive\" ) )