我試圖以編程方式運行一系列命令,讀取錯誤代碼,並檢測這些代碼是否顯示成功或失敗,以便我可以做出相應的響應。如何檢測哪個程序返回了錯誤代碼?
目前我的命令使用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