开发者

How to execute CMD commands by catching the error code and taking appropriate actions

开发者 https://www.devze.com 2023-02-20 18:33 出处:网络
I would like to execute Command Prompt(CMD) programmatically and then execute a series of commands and check if the commands return success or failure.

I would like to execute Command Prompt(CMD) programmatically and then execute a series of commands and check if the commands return success or failure.

I have seen how to execute a batch file or general commands but how can I catch the errors and carry on with further commands in the same 开发者_运维问答window.

Like,

DiskRaid

create

list

select

name

extend

detail

And if any of the above commands return an Error, I have to store the error and proceed with other operations. So that at the end, I can easily figure out which commands went through successfully and which failed.

Any idea of how this can be implemented using C# or C++?


If you only want the exit code of a process, this should help:

Process test = new Process();
test.StartInfo = psi;
test.EnableRaisingEvents = true;
test.Exited += new EventHandler(test_Exited);

...    

void test_Exited(object sender, EventArgs e)
{
  int exitCode = ((Process)sender).ExitCode;
  switch (exitCode)
  {
     case 0:
         DoSomething();
         break;
     case 1:
         .......
  }

With the OutputDataReceived event you can asynchronously read the output of the process. More information here: MSDN


If you need to do complex commandline operations, I would advice you to use a scripting language or cli script to do the logic of the command line operations, and call this script from c++. This approach is easier to change, and makes it easier to dictate how the input to your c++/c# program looks like. It might then be as easy as just making the call to the script and read the exit value.

To run a cli script use the system command

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号