0

我正在尝试使用 FC 来比较文件,但想获取 FC 命令的输出,将其解析出来,并声明变量以将源文件复制到不匹配的远程文件上,本质上是同步的。

我的代码非常简单,因为fc可以满足我的一切需求:

 @echo off

set source=C:\source\
set remote=C:\remote\

fc /b %source%\*.* %remote%\*.*

如果文件不同,则 fc 输出示例:

00000000 47 55
00000001 44 48
00000002 55 61
FC: C:\source\test.txt longer than C:\remote\test.txt

最后一行是我想要的,我想用文件路径解析并使用它们来声明要使用的变量

xcopy %sourcefile% %remotefile%

这需要能够解析多个 fc 文件输出。

4

2 回答 2

2

FC.EXE将设置一个 ErrorLevel 如下

-1 Invalid syntax (e.g. only one file passed) 
0 The files are identical.
1 The files are different.
2 Cannot find at least one of the files.

您的脚本可能是(带有一些调试echocopy命令注释REM)。

@echo off

set "source=C:\source"
set "remote=C:\remote"

for /F "delims=" %%G in ('dir /B "%source%\" /A:-D') do (
  >NUL 2>&1 FC /b "%source%\%%~G" "%remote%\%%~G"
  if errorlevel 1 (
    echo %%G files differ or remote does not exist
    REM copy /B /Y "%source%\%%~G" "%remote%\%%~G"
  ) else (
    echo %%G files match
  )
)

但是,ROBOCOPY.exe- 强大的文件和文件夹复制提供了更高级的选项,包括递归到子文件夹。

如果ROBOCOPY由于任何原因无法使用,则上述脚本更改如下:

@ECHO OFF
SETLOCAL EnableExtensions

set "sourceMain=C:\source"
set "remoteMain=C:\remote"

call :subFolder "%sourceMain%" "%remoteMain%" "%sourceMain%"

rem traverse source subfolder structure
for /F "delims=" %%g in ('dir /B /S "%source%\" /A:D 2^>NUL') do (
  call :subFolder "%sourceMain%" "%remoteMain%" "%%~g"
)
ENDLOCAL
goto :eof

:subFolder
    rem adapted original script 
set "sourceRoot=%~1"
set "remoteRoot=%~2"

set "source=%~3"
call set "remote=%%source:%sourceRoot%=%remoteRoot%%%"     compute target folder

ECHO *** comparing "%source%" vs. "%remote%" ***
rem next command creates target folder if it does not exists yet
MD "%remote%" 2>NUL

for /F "delims=" %%G in ('dir /B "%source%\" /A:-D 2^>NUL') do (
  >NUL 2>&1 FC /b "%source%\%%~G" "%remote%\%%~G"
  if errorlevel 1 (
    echo %%G files differ or remote does not exist
    REM copy /B /Y "%source%\%%~G" "%remote%\%%~G"
  ) else (
    echo %%G files match
  )
)
goto :eof

请注意,变量编辑/替换的目标文件夹计算出于方便的原因从%%g循环体移动到:subFolder子例程:无需激活延迟扩展
请注意,%%G循环保持不变。

于 2016-10-19T21:29:08.483 回答
0

(代表 OP 发布解决方案)

感谢ashipflJosefZ,我发现 ROBOCOPY 正是我所需要的。SS64.com 有一个非常适合我的示例;下面的代码及其 ROBOCOPY 页面的链接:

@ECHO OFF
SETLOCAL

SET _source=\\FileServ1\e$\users

SET _dest=\\FileServ2\e$\BackupUsers

SET _what=/COPYALL /B /MIR
:: /COPYALL :: COPY ALL file info
:: /B :: copy files in Backup mode. 
:: /MIR :: MIRror a directory tree 

SET _options=/R:0 /W:0 /LOG:C:\batch\RoboLog.txt /NFL /NDL
:: /R:n :: number of Retries
:: /W:n :: Wait time between retries
:: /LOG :: Output log file
:: /NFL :: No file logging
:: /NDL :: No dir logging

ROBOCOPY %_source% %_dest% %_what% %_options%

http://ss64.com/nt/robocopy.html

于 2016-10-23T19:45:29.423 回答