windows - 批处理循环错误 - 仅复制 1 个文件

标签 windows shell batch-file scripting

我正在尝试运行一个 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

我错过了什么?

最佳答案

@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!
)

关于windows - 批处理循环错误 - 仅复制 1 个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25755117/

相关文章:

windows - 如何使用 UAC 提升 Perl 进程

windows - Windows + 空格键的用途是什么?

shell - 命令 "netstat -p"不显示 pid

linux - 如何在文件中的特定列中搜索 shell 中的字符串?

Windows cmd : How to find and kill . 运行并使用 wscript 隐藏的 bat 文件?

windows - SetErrorMode没有效果?

c - 未定义对 "sleep"的引用,但我确实包含了 <unistd.h>

c - 为什么我们不能在 Linux 中通过 system() 系统调用更改目录?

windows - 在 CMD/PowerShell 中为当前登录用户创建用户帐户

java - 将值从 .txt 传递到 HTML 文本框(使用 Batch、Java 或 PHP)