我为内部服务器构建了一个web服务,我想发送一个命令并让它启动一个进程。所以我想像这样发送一个命令:
http://machine:999/execute?path=c:\scripts\dostuff.exe&args=-test
然后端点将执行以下操作:
public ActionResult(string path, string args)
{
var proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = path;
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.StartInfo.RedirectStandardOutput = true;
//Hook into all standard output here
//Block until process is returned - Async Controller action
return Content(output.ToString())
}
我希望能够捕获可执行文件生成的所有错误消息和标准输出。可执行文件可以是控制台应用程序或PowerShell脚本。做这样的事情的最佳方法是什么?
答案 0 :(得分:1)
使用proc.StandardOutput.ReadToEnd()将重定向的输出流读取到结尾,然后返回。
您可能还希望将RedirectStandardError设置为True,并使用proc.StandardError执行相同操作以获取错误消息。您可以生成后台线程,以便在主线程中读取标准输出的同时读取标准错误。