【问题标题】:Check if process indirectly resulted in an error检查过程是否间接导致错误
【发布时间】:2015-06-11 11:13:05
【问题描述】:

我使用以下代码打开 cmd 并使用配置文件运行 SQL Server setup.exe。

            ProcessStartInfo pStartInfo = new ProcessStartInfo();
            pStartInfo.FileName = "cmd.exe";
            pStartInfo.Arguments = "/c /q setup.exe /c /q /configurationFile=../configurationFile.ini";
            pStartInfo.WorkingDirectory = installDir + @"\SQL Server Unpacked";
            pStartInfo.CreateNoWindow = true;
            pStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            pStartInfo.UseShellExecute = false;
            pStartInfo.RedirectStandardInput = true;
            pStartInfo.RedirectStandardOutput = true;
            pStartInfo.RedirectStandardError = true;

            Process p = new Process();
            p.StartInfo = pStartInfo;

            lb_SQLServerReadout.Text = "Please wait while the setup runs";
            p.Start();

这一切正常。它将尝试使用配置文件的详细信息进行安装,如果配置文件包含无效的详细信息,则 setup.exe 将出错并且无法安装。

我希望能够获取该错误代码并将其写入表单上的标签,以便用户通过某种方式知道发生了错误以及发生错误的原因。我考虑过使用Process.StandardError.ReadToEnd,但它总是会返回null。我相信这是因为Process 本身是 cmd,而不是 setup.exe(实际发生错误的地方)。

我读到可以使用echo %errorlabel% 获取 cmd 中的最后一个错误代码,当我手动运行它时确实有效,所以我尝试在我的代码中实现它:

            p.StandardInput.WriteLine("echo %errorlevel%");
            string s = p.StandardOutput.ReadLine();
            p.WaitForExit();

我希望将s 设置为echo %errorlevel% 输入的输出,但它只是设置为null

如何通过我的 cmd Process 获取 SQL Server 设置的错误代码?

顺便说一句,我考虑过将 setup.exe 作为Process 运行,但它需要提升,这意味着启用UseShellExecute,这反过来意味着禁用RedirectStandardError,这将阻止我获得还是错误代码。

【问题讨论】:

    标签: c# sql-server process cmd


    【解决方案1】:

    这都不是必需的,cmd.exe /c 调用的“可执行文件”的退出代码将是 cmd.exe 本身的退出代码。

    你也可以在命令行上试试这个:

    c:\> cmd.exe /c app.exe make-it-fail
    c:\> echo %errorlevel%
    

    第二行将打印“app.exe make-it-fail”的退出代码。

    所以,只需读取Process.ExitCode 属性的值,在Process.WaitForExit() 之后。

    我不知道setup.exe(SQL Server 的)在失败时设置了哪些特定值。应该与0 不同(按照惯例)。

    【讨论】:

      猜你喜欢
      • 2014-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      相关资源
      最近更新 更多