某些命令只会返回error level,而要添加互操作性,.bat文件的返回值,exit code应该最后指定,那么需要,在这个单行的命令后面单个添加处理error level
的语句,最后再做统一的抛出处理,一个robo copy,批量拷贝,很实用的例子,可以作为参考,以下命令通过测试
@echo off ROBOCOPY c:\a c:\d /MIR /LOG:c:\d\log1.txt if %ERRORLEVEL% GEQ 8 echo error encountered errorlevel:%errorlevel% & goto throw ROBOCOPY c:\b c:\c /MIR /LOG:c:\c\log2.txt :throw if %ERRORLEVEL% GEQ 16 echo ***FATAL ERROR*** & goto end if %ERRORLEVEL% EQU 15 echo OKCOPY + FAIL + MISMATCHES + XTRA & goto end if %ERRORLEVEL% EQU 14 echo FAIL + MISMATCHES + XTRA & goto end if %ERRORLEVEL% EQU 13 echo OKCOPY + FAIL + MISMATCHES & goto end if %ERRORLEVEL% EQU 12 echo FAIL + MISMATCHES& goto end if %ERRORLEVEL% EQU 11 echo OKCOPY + FAIL + XTRA & goto end if %ERRORLEVEL% EQU 10 echo FAIL + XTRA & goto end if %ERRORLEVEL% EQU 9 echo OKCOPY + FAIL & goto end if %ERRORLEVEL% EQU 8 echo FAIL & goto end if %ERRORLEVEL% EQU 7 echo OKCOPY + MISMATCHES + XTRA & goto end if %ERRORLEVEL% EQU 6 echo MISMATCHES + XTRA & goto end if %ERRORLEVEL% EQU 5 echo OKCOPY + MISMATCHES & goto end if %ERRORLEVEL% EQU 4 echo MISMATCHES & goto end if %ERRORLEVEL% EQU 3 echo OKCOPY + XTRA & goto end if %ERRORLEVEL% EQU 2 echo XTRA & goto end if %ERRORLEVEL% EQU 1 echo OKCOPY & goto end if %ERRORLEVEL% EQU 0 echo No Change & goto end :end if %ERRORLEVEL% GEQ 8 exit %ErrorLevel% exit 0
robo copy命令的说明可以见网址:http://ss64.com/nt/robocopy-exit.html
a sample call in c# with exitcode handling
void Main()
{
Process processer = new Process();
processer.StartInfo.FileName = @"c:\a\testrobocopy.bat";
processer.StartInfo.Arguments = null;
processer.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processer.StartInfo.RedirectStandardOutput = true;
processer.StartInfo.RedirectStandardError = true;
processer.StartInfo.UseShellExecute = false;
processer.StartInfo.CreateNoWindow = true;
processer.EnableRaisingEvents = true;
processer.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceived);
processer.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataReceived);
processer.Start();
processer.BeginOutputReadLine();
processer.BeginErrorReadLine();
processer.WaitForExit();
Console.WriteLine (processer.ExitCode);
//Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
}
private void ErrorDataReceived(object sendingProcess,
DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
Console.WriteLine ("error:"+outLine.Data);
}
}
private void OutputDataReceived(object sendingProcess,
DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
Console.WriteLine ("output:"+outLine.Data);
}
}
// Define other methods and classes here
//call kernel32.dll method to invoke some process to complete our job and check results of the processor created jobs