Hi, I'm attempting to run a series of commands programmatically, read the error codes, and detect if these codes indicate success or failure so I can respond accordingly.
Currently my commands are using psexec which then launches robocopy. I've noted that while most commands return an error code of 0 if the program is successful, robocopy is odd in that it returns values in the range of 0-8 even if the operation is successful, so I am adding some extra logic in my error detection to note when robocopy returns an error code which otherwise suggests a failure.
The problem is that in this same set of commands I'm using PSExec to launch various other executables and batch files, so I need an error detection solution that allows me to know when robocopy is the one returning these error codes or if it's PSExec because an error code of 5 in robocopy is fine usually whereas an error code of 5 in PSExec says that access is denied.
So my question is, how do I know which program has returned the error code? I'm using c# .NET 4.0, and I'm using the Process class to programmatically launch these programs. I set the program name as psexec, and the arguments include the robocopy or other programs. I then run, wait for the exit, and store the error code, then attempt to parse it.
What do you all suggest?
Here is a code snippet:
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