我试图以编程方式运行一系列命令,读取错误代码,并检测这些代码是否显示成功或失败,以便我可以做出相应的响应。如何检测哪个程序返回了错误代码?
目前我的命令使用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
我面临的问题是,我总是使用PSExec启动程序,无论它们是Robocopy还是其他可执行文件或批处理文件,因此文件名始终为psexec,但参数始终不同。我的问题是如何确定哪些程序返回了代码? PSExec和其他程序都正在执行 - 但是在robocopy甚至执行之前,PSExec可能会失败并显示5访问被拒绝的错误代码 - 我如何确定哪个错误代码来自哪个程序?还是我只是左猜? – Ben 2010-07-07 18:37:00
啊。得到它了。不幸的是,无论应用程序是成功还是失败,只要能够成功启动应用程序,'PsExec'就会一直返回成功。因此,无论您从启动PsExec获得的错误代码始终来自PsExec。如果该代码表示成功,那么您尝试从实际应用程序中测试代码。一个混乱的方法是使用'PsExec'启动一个脚本,该脚本将启动您的应用程序,获取它的退出代码并将代码写入文件。然后您可以从文件中读取代码。 – 341008 2010-07-07 18:56:01
谢谢。正如我担心的那样:/我想我会对结果进行统计分析并存储robocopy命令的数量,并将它们与0-8范围内可能失败的命令数进行比较。如果失败次数等于或超过了robocopy命令的数量,那么问题几乎肯定来自PSExec/windows,我可以警告用户。否则,我只能显示统计数据,并让用户根据计划决定是否事情正在进行,或者是否需要亲自调查。 – Ben 2010-07-07 19:04:08