将错误级别描述回显到日志文件

将错误级别描述回显到日志文件

请原谅我的无知。我对编写批处理文件还很陌生。

我正在将文件从一个映射服务器驱动器复制到另一个映射服务器驱动器,并在复制完成后创建一个日志文件。

我的脚本如下。

@echo off

copy /V "\\server_A\source\%date:~4,2%-%date:~7,2%-%date:~10,4%\*.txt" "\\server_B\destination\" >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt"
if %errorlevel% NEQ 0 goto ERROR
echo Copied file successfully >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt"
echo The files were copied to destination: \\server_B\destination\ on %Date% at %Time% >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt"
goto EOF


:ERROR
echo Copy failed on %Date% %Time% >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt"
echo Errorlevel %errorlevel% >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt"
goto EOF

:EOF
pause

目前,日志文件运行完美,成功。

但是,如果发生故障(即不存在指定的源文件夹),它不会将“系统找不到指定的路径”消息发送到日志文件。此外,它仍然会回显“错误级别 1”,尽管“系统找不到指定的路径”应该是错误级别 3(无论如何,据我理解)。

任何帮助,将不胜感激!

答案1

使用command >FileLogOut.txt 2>&1重定向 Windows cmdstdoutstderr到单个文件

copy /V "\\server_A\source\%date:~4,2%-%date:~7,2%-%date:~10,4%\*.txt" "\\server_B\destination\" >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt" 2>&1

您可以使用以下方式if (condition) goto error替换command if return non 0 goto errorcommand || goto error

@echo off

copy /V "\\server_A\source\%date:~4,2%-%date:~7,2%-%date:~10,4%\*.txt" "\\server_B\destination\" >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt" 2>&1 || goto ERROR

echo Copied file successfully >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt"
echo The files were copied to destination: \\server_B\destination\ on %Date% at %Time% >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt"
goto EOF


:ERROR
echo Copy failed on %Date% %Time% >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt"
echo Errorlevel %errorlevel% >> "\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt"
goto EOF

:EOF
pause

  • &&另一种方法是使用变量和运算符||
@echo off & setlocal

set "_dest=\\server_B\destination\"
set "_srcs=\\server_A\source\%date:~4,2%-%date:~7,2%-%date:~10,4%\*.txt"
set "_logs=\\server_B\Logs\log_%date:~4,2%-%date:~7,2%-%date:~10,4%.txt"
set "_mssg=The files were copied to destination: \\server_B\destination\ on %Date% at %Time%"

copy /v "%_srcs%" "%_dest%" >> "%_log%" 2>&1 && (
     echo\Copied file successfully & echo\%_mssg% 
    ) >>"%_log%" || >>"%_log%" ( 
     echo\Copy failed on %Date% %Time%
     echo\Errorlevel %errorlevel%
    ) 

endlocal | pause 

其他资源:

相关内容