batch-file - robocopy 在批处理文件中的标准输出和错误输出

发布时间 2023-03-27 15:15:08作者: 西秀岭

batch-file - robocopy 在批处理文件中的标准输出和错误输出

标签 batch-file robocopy

我用 机器人复制在我的批处理文件中复制文件夹。我希望标准输出转到一个日志文件,错误消息转到另一个日志文件。

我尝试了以下方法:

robocopy Z\BR  "C\WIN"  /E /LOG+:STANDART.LOG  2 /LOG+:ERROR.LOG 

但是“如果没有错误”(不确定 OP 是什么意思)并且标准输出将转到 ERROR.LOG。
谁能帮我?

 

最佳答案

您同时拥有标准日志和错误日志的问题的解决方案是创建一个临时日志,然后 决定如何处理它。

我还发现了 ROBOCOPY 和错误报告的一些问题。

1) 如果您使用内置 /log:file 创建日志文件或 /log+:file ,并不是所有的错误都会出现在日志中。
2) 此外,并非所有错误都会报告给 ERRORLEVEL .
3) 最后,成功复制可能会报告为 ERRORLEVEL 1 .

为了解决这个问题,我使用了 3 种方法来捕获所有错误。首先,我将 STDOUT 重定向到一个临时日志文件,然后在该日志文件中的两个位置检查“ERROR”一词,第三个位置还检查 ERRORLEVEL。

部分问题在于 ROBOCOPY put 的两个 EOF 它的日志文件末尾的字符。通常这不是问题,除非像我在这里那样尝试连接文件。当您通常连接文件时,最后一个字符(EOF 字符)会被覆盖。但是如果有两个 EOF 字符,附加到文件的所有内容都会在此之后进行,因此当您以正常方式访问文件时,您看不到任何附加数据。

setlocal

set Source=<somedir>
set Dest=<someotherdir>
set Files=*.* or afile anotherfile yetathridfile
set Options=

set STDLog=STANDART.LOG
set ErrLog=ERROR.LOG
set TMPLog=TMP.LOG
set err=

:: If nessicary make 0 byte log files
if not exist %ErrLog% copy nul %ErrLog%
if not exist %STDLog% copy nul %STDLog%

:: Create a header in the temporary log file to make each entry more visable
echo.>%TMPLog%
echo ===============================================================================>> %TMPLog%
echo ===============================================================================>> %TMPLog%
echo.>> %TMPLog%
echo Started : %date:~-4%/%date:~4,5% %time%>> %TMPLog%

:: Record how ROBOCOPY was called
echo ROBOCOPY %source% %dest% %files% %options%>>%TMPLog%

:: Call ROBOCOPY and redirect STDOUT to %TMPLog%
ROBOCOPY %source% %dest% %files% %options%>>%TMPLog%

:: Depending on the error, it may be in the first or third token.
:: So we need to check both.
for /f "tokens=1,3" %%x in (%TMPLog%) do (
  if "%%x"=="ERROR" SET err=TRUE
  if "%%y"=="ERROR" SET err=TRUE
)

:: The error also MAY be reported via ERRORLEVEL
:: 0 = No error, all files skipped (because they are the same in both dirs)
:: 1 = No error, some or all files copied.
:: 2 = Destination DIR contains extra files the source does not.
set error=%errorlevel%
if %errorlevel% gtr 2 set err=TRUE

if "%err%"=="TRUE" (
  REM However we got the error, copy the temp log to the error log.
  REM Copy both files as ASCII. Otherwise you'll have trouble. (This caused me BIG headaches.)
  REM The command states that the two source files are ASCII and the destination is ASCII
  copy /a %ErrLog% + /a %TMPLog%=/a %ErrLog%
) else (
  REM If no errors, copy the temp log to the standard log.
  REM Copy both files as ASCII. Otherwise you'll have trouble. (This caused me BIG headaches.)
  copy /a %STDLog% + /a %TMPLog%=/a %STDLog%
)

:: Delete the temporary log file
del %TMPLog%

:: set the errorlevel to ROBOCOPY's errorlevel and reset all variables
endlocal & exit /b %error%

 

关于batch-file - robocopy 在批处理文件中的标准输出和错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12334853/