我正在尝试使用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文件输出。
答案 0 :(得分:2)
FC.EXE
will set an ErrorLevel as follows:
-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.
您的脚本可能(通过echo
注释了一些调试copy
和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
- Robust File and Folder Copy提供了更高级的选项,包括递归到子文件夹。
如果您因任何原因无法使用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
请注意,由Variable Edit/Replace计算的目标文件夹计算从%%g
循环体移动到:subFolder
子例程,原因很简单:无需激活delayed expansion。
请注意%%G
循环保持不变。
答案 1 :(得分:0)
(代表OP发布解决方案)。
感谢 ashipfl 和 JosefZ ,我发现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%