未获取进程的正确错误代码



我正在尝试获取一个批处理脚本的返回代码,实习生会调用其他几个批处理和exe文件。当我在CMD窗口中执行脚本并打印错误级别时,我会得到正确的错误代码,但当我在C#中对进程执行同样的操作时,我总是得到0作为错误代码。

这是我的C#代码

private Process ExecuteBatchFile(string batchFile)
{
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
RedirectStandardOutput = false,
RedirectStandardError = false,
UseShellExecute = true,
FileName = "CMD.exe",
WorkingDirectory = Constants.ToolsPath,
Arguments = $"/c "{batchFile} & pause""
}
};
process.Start();
return process;
}
batchFile = $"testScript.bat -tns {Project.TnsName} & echo Error: %errorlevel%";

我得到的回波输出是Error: 0和进程。ExitCode值为0

如果我打开CMD窗口并输入

cmd.exe /c "testScript.bat -tns MYTNS & echo Error: %errorlevel% & pause"

我得到了正确的错误级别值。

我猜这与批处理脚本有关,但我不明白为什么它在CMD窗口中有效,而在C#进程中无效,尤其是因为我使用相同的方法连接网络驱动器和执行exe文件。

编辑:不使用CMD:的代码

private Process ExecuteBatchFile(string batchFile, string args)
{
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
RedirectStandardOutput = false,
RedirectStandardError = false,
UseShellExecute = true,
FileName = batchfile,
WorkingDirectory = Constants.ToolsPath,
Arguments = args
}
};
process.Start();
return process;
}
batchFile = "testScript.bat";
args = $"-tns {Project.TnsName}";

我怀疑你的.bat文件中有一行类似于exit /b 1。从cmd实例运行此.bat文件时,/b标志允许.bat文件退出,而无需关闭父cmd进程(非常适合手动运行!(。

不幸的是,这意味着当您执行Process.Start("testScript.bat");时,C#会在后台使用cmd来运行您的bat。.bat文件带着/b标志退出,向父cmd进程发出不应该崩溃的信号,因此它退出";"成功";(退出代码0(。

你有两个选择:

  1. 删除/b标志(它将正确返回退出代码.bat>cmd>process.ExitCode(-尽管这意味着通过cmd实例手动执行.bat将在退出时终止父cmd
  2. 添加到您的C#代码中,编写一个包装器.bat,它将所有参数管道传输到您的bat文件并正确返回%exitcode%
private int ExecuteBatWithWrapper(string batFile, string args){
string runnerPath = Path.Combine(Path.GetDirectoryName(batFile), "runner.bat");
File.WriteAllText(runnerPath, $"call {batFile} %*nexit %ERRORLEVEL%");
Process process = Process.Start(runnerPath, args); //Alternatively construct with ProcessStartInfo
File.Delete(runnerPath);
return process.ExitCode;
}

(当然,如果这在任何类型的重要环境中使用,您应该将其合并到某种using语句中,该语句在处理时会删除runner,但这只是概念的证明(

请参阅https://bytes.com/topic/c-sharp/answers/511381-system-diagnostics-process-bat-file-always-returns-exit-code-0-a#post1989782对于类似的后

相关内容

最新更新