我正在尝试以编程方式运行一系列命令,读取错误代码,并检测这些代码是否指示成功或失败,以便我可以做出相应的响应。
目前我的命令正在使用 psexec,然后启动 robocopy。我注意到,虽然大多数命令在程序成功时返回错误代码 0,但 robocopy 很奇怪,即使操作成功,它也会返回 0-8 范围内的值,所以我在其中添加了一些额外的逻辑当 robocopy 返回错误代码时,我的错误检测要注意,否则会提示失败。
问题是,在同一组命令中,我使用 PSExec 来启动各种其他可执行文件和批处理文件,所以我需要一个错误检测解决方案,让我知道什么时候 robocopy 是返回这些错误代码的那个,或者它是否是 PSExec,因为robocopy 中的错误代码 5 通常很好,而 PSExec 中的错误代码 5 表示访问被拒绝。
所以我的问题是,我怎么知道哪个程序返回了错误代码?我正在使用 c# .NET 4.0,并且正在使用 Process 类以编程方式启动这些程序。我将程序名称设置为 psexec,参数包括 robocopy 或其他程序。然后我运行,等待退出,并存储错误代码,然后尝试解析它。
大家有什么建议?
这是一个代码片段:
foreach (var command in commands)
{
// TODO: Add exception handling
string processName = command.Split(delimiters).ToList().ElementAt(0); // split up command into pieces, select first "token" as the process name
string commandArguments = command.Replace(processName + " ", ""); // remove the process name and following whitespace from the command itself, storing it in a new variable
Process commandProcess = new Process(); // declare a new process to be used
commandProcess.StartInfo.FileName = processName; // add file start info for filename to process
commandProcess.StartInfo.Arguments = commandArguments; // add file start info for arguments to process
commandProcess.StartInfo.UseShellExecute = false; // skip permissions request
commandProcess.Start(); // start process according to command's data
commandProcess.WaitForExit(); // wait for the process to exit before continuing
bool commandSuccessful = ParseCommandErrorCode(commandProcess, commandProcess.ExitCode); // grab error code
if (!commandSuccessful)
{
// ERROR! abort operation and inform the user of the last completed operation, and how many commands have not been run
} // end if
Console.WriteLine("Error code: {0}", commandProcess.ExitCode); // print error code
commandProcess.Close(); // close process
} // end foreach