如何获取netsh的错误码?

问题描述 投票:0回答:1

我捕获了这样的进程的输出退出代码

Process proc = new Process
{
    StartInfo =
    {
        RedirectStandardOutput = true,
        UseShellExecute = false,
        FileName = Environment.SystemDirectory + "\\netsh.exe",
        Arguments = "http delete urlacl url=http://+:8080/my/Url/Suffix"
    }
};
proc.Start();
proc.WaitForExit();

int exitCode = proc.ExitCode;
string output = proc.StandardOutput.ReadToEnd();

当我检查退出代码时,它是

1

当我检查流程的输出时,它是

URL预留删除失败,错误:2
系统找不到指定的文件。

输出正是我所期望的。我正在尝试删除不存在的预订。我需要的是隐藏在输出中的错误代码。我是否需要编写自己的自定义解析器来考虑 netsh 可能向我抛出的所有奇怪消息?

有没有简单的方法获取错误代码?

c# cmd
1个回答
0
投票

我想我已经想出了一个很好的解决方案,假设你不介意使用 RegEx。

从我看到的法语输出消息语法的示例中,我认为这个正则表达式应该适用于任何语言,但我还没有测试过它。

  • ^\\r\\n.+: (\d+)\\r\\n.+\\r\\n$
  • RegEx101

示例代码:

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "netsh.exe";
startInfo.Arguments = ...;
startInfo.Verb = "runas";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();

if (process.ExitCode == 0)
    return; // success.
else if (process.ExitCode == 1)
{
    const string NETSH_ERROR_REGEX = "^\\\\r\\\\n.+: (\\d+)\\\\r\\\\n.+\\\\r\\\\n$";
    Match match = Regex.Match(output, NETSH_ERROR_REGEX);
    if (match.Groups is object && int.TryParse(match.Groups.Values.Single().Value, out int i))
        return i;
}
throw new Exception($"\"{startInfo.FileName} {startInfo.Arguments}\" exited with {process.ExitCode}, see inner exception for output.", new Exception(output.Replace("\r", "\\r").Replace("\n", "\\n")));
© www.soinside.com 2019 - 2024. All rights reserved.