【问题标题】:COPY function in FOR loop (batch)FOR循环中的COPY函数(批处理)
【发布时间】:2015-07-07 21:11:23
【问题描述】:

我正在编写一个可以同步 2 个文件夹的批处理脚本。我所说的同步的意思是:脚本将比较每个文件夹的每个文件,并且它只会保留每个文件夹中最新的文件。它基本上是一个智能备份程序。

这是我遇到问题的代码部分(整个脚本可以在here找到):

for /d /r %drivePath% %%d in (*) do (
  set currentDriveFolderPath=%%d
  if not exist "%devicePath%!currentDriveFolderPath:~%driveLength%!" (
    mkdir "%devicePath%!currentDriveFolderPath:~%driveLength%!"
  )
  for %%f in (*.*) do (
    set currentFile=%%f
    if exist "%devicePath%!currentDriveFolderPath:~%driveLength%!!currentFile!" (
      set currentDriveFile="!currentDriveFolderPath!\!currentFile!"
      set currentDeviceFile="%devicePath%!currentDriveFolderPath:~%driveLength%!!currentFile!"
      call:compareModifiedDate !currentDriveFile! !currentDeviceFile!
      if !recent! == file1 (
        copy /y !currentDriveFile! !currentDeviceFile!
      ) else if !recent! == file2 (
        copy /y !currentDeviceFile! !currentDriveFile!
      )
    ) else (
      set source
      copy /y !currentDriveFile! !currentDeviceFile!
    )
  )
)

for /d /r %devicePath% %%d in (*) do (
  set currentDeviceFolderPath=%%d
  if not exist %drivePath%!currentDeviceFolderPath:~%deviceLength%! (
    mkdir "%drivePath%!currentDeviceFolderPath:~%deviceLength%!"
    for %%f in (*.*) do (
      set currentFile=%%f
      if not exist "%drivePath%!currentDeviceFolderPath:~%DeviceLength%!!currentFile!" (
        copy /y !currentDriveFile! !currentDeviceFile!
      )
    )
  )
)

我的问题是:在源路径和目标路径每次都在变化的情况下,我该怎么做才能在 FOR 循环中调用 COPY 函数?

【问题讨论】:

  • 批处理还是 Bash?两个不同的东西
  • @UnknownOctopus - 好吧,脚本显然不是 bash,如果您对 Windows 批处理脚本有所了解,您会立即认出它。此外,OP 始终使用术语批处理和批处理脚本,并使用批处理文件标签。为什么您会推测问题可能不是 Windows 批处理脚本?
  • @dbenham 因为 OP 的链接使用 bash 突出显示。这就是为什么。而且标签并不总是正确的,它们被滥用了很多次。

标签: batch-file for-loop copy


【解决方案1】:

我什至不会尝试找出您的代码 - 这太痛苦了 - 知道有一个更简单的解决方案。

我相信您只需要两个简单的 XCOPY 语句,每个方向一个,使用 /D 选项使两个文件夹层次结构与每个文件中每个文件的最新版本同步。还有更多内容需要充实,但我认为这应该让您继续前进。您也可以以类似的方式使用 ROBOCOPY - 它提供了更多选项并且更健壮,但它的语法也更复杂,可以得到您想要的。

假设您的根路径是 d:\path1e:\path2

xcopy d:\path1 e:\path2 /e /d /y
xcopy e:\path2 d:\path1 /e /d /y

我已经进行了一些初步测试,它似乎有效,但我还没有进行严格的测试。请务必进行大量测试以确保我没有遗漏任何内容。

【讨论】:

  • 非常感谢@dbenham!!!我还是批处理新手,所以我不知道 xcopy 命令中的 /d 选项存在......这也是我的代码如此混乱的原因。但是你能告诉我是否可以像我问的那样在 for 循环中执行复制命令?
  • setlocal enabledelayedexpansion 是可能的。
  • 还可以考虑使用call :SOMELABEL param1 param2,以便将 SOMELABEL 用作一种函数。您需要了解call 在这种情况下会做什么。运行call /? 寻求帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 2015-04-17
  • 1970-01-01
  • 2023-04-08
相关资源
最近更新 更多