【问题标题】:Batch loop error - only 1 file is copied批处理循环错误 - 仅复制 1 个文件
【发布时间】:2014-09-09 23:33:34
【问题描述】:

我正在尝试运行一个 bat 文件:

  1. 创建文件夹
  2. 搜索所有带有.log 扩展名的文件
  3. 将文件复制并重命名为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!
    )
    

    【讨论】:

    • +1,大概有30%的问题与延迟展开有关。
    【解决方案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显示 而不是执行 命令 - 更容易在出现错误时调试...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-21
      • 2021-01-01
      • 2023-03-23
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多