如何通过捕获错误代码并采取适当的操作来执行 CMD 命令

发布于 2024-10-29 15:25:08 字数 399 浏览 2 评论 0原文

我想以编程方式执行命令提示符(CMD),然后执行一系列命令并检查命令是否返回成功或失败。

我已经了解了如何执行批处理文件或一般命令,但如何捕获错误并在同一窗口中继续执行进一步的命令。

喜欢,

磁盘阵列

<块引用>

创建

列表

选择

姓名

延长

详情

如果上述任何命令返回错误,我必须存储错误并继续执行其他操作。这样最后我就可以轻松地找出哪些命令成功执行,哪些命令失败。

知道如何使用 C# 或 C++ 实现这一点吗?

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++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风柔一江水 2024-11-05 15:25:08

如果您只需要进程的退出代码,这应该会有所帮助:

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:
         .......
  }

使用 OutputDataReceived 事件,您可以异步读取进程的输出。
更多信息请参见:MSDN

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

乱世争霸 2024-11-05 15:25:08

如果您需要执行复杂的命令行操作,我建议您使用脚本语言或cli脚本来执行命令行操作的逻辑,并从c ++调用此脚本。这种方法更容易更改,并且更容易指定 C++/C# 程序的输入。然后,它可能就像调用脚本并读取退出值一样简单。

要运行 cli 脚本,请使用系统命令

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文