【问题标题】:Batch loop error - only 1 file is copied批处理循环错误 - 仅复制 1 个文件
【发布时间】:2014-09-09 23:33:34
【问题描述】:
我正在尝试运行一个 bat 文件:
- 创建文件夹
- 搜索所有带有
.log 扩展名的文件
- 将文件复制并重命名为
MyFile_customString.log 到另一个文件夹
到目前为止,我是这样做的:
@echo off
set host_name=%1
set origin_path=%2
set destiny_path=%3
set destiny_host_path=%destiny_path%\%host_name%\
mkdir .\%destiny_host_path%
FOR %%G IN (%origin_path%/*.log) DO (
SET _fileName=%%G
SET _custom=%_fileName:.log=_%%host_name%.log%
xcopy /Y /F %origin_path%\%_fileName% %destiny_host_path%\%_custom%
)
并且在 origin_path 中有 MyTest.log 和 MyTest2.log 文件,只有 MyTest2.log 文件被复制到 destiny_host_path
我错过了什么?
【问题讨论】:
标签:
windows
shell
batch-file
scripting
【解决方案1】:
@echo 之后的批处理文件顶部需要 SetLocal EnableDelayedExpansion
在您的代码中:
FOR %%G IN (%origin_path%/*.log) DO (
SET _fileName=%%G
SET _custom=%_fileName:.log=_%%host_name%.log%
xcopy /Y /F %origin_path%\%_fileName% %destiny_host_path%\%_custom%
)
应该是:
FOR %%G IN (%origin_path%/*.log) DO (
SET "_fileName=%%G"
FOR %%H in (!host_name!) Do (
SET "_custom=!_fileName:.log=_%%H.log!"
)
xcopy /Y /F !origin_path!\!_fileName! !destiny_host_path!\!_custom!
)
【解决方案2】:
FOR %%G IN (%origin_path%\*.log) DO (
xcopy /Y /F "%origin_path%\%%G" "%destiny_host_path%\%%~nG_%host_name%.log"
)
(未经测试)
在这种情况下不需要delayedexpansion。
有关使用~-modifiers 提取部分文件名的信息,请参阅提示中的for /? |more。
在您的原始文件中,您的 %s 在 set _custom 行中是不平衡的(假设 % 在这种情况下是正确的)。
提示:将xcopy 临时替换为echo xcopy 以显示 而不是执行 命令 - 更容易在出现错误时调试...