2

I've built a webservice for an internal server that I want to send a command to and have it launch a process. So I want to send a command to it like this:

http://machine:999/execute?path=c:\scripts\dostuff.exe&args=-test

The endpoint would then do something like this:

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())
}

I want to be able to capture all the error messages and standard output generated by the executable. The executable could be anything like a console application or a powershell script. What's the best approach for doing something like this?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Micah
  • 111,873
  • 86
  • 233
  • 325

1 Answers1

1

Use proc.StandardOutput.ReadToEnd() to read the redirected output stream to the end, and return that.

You may also want to set RedirectStandardError to True and do the same thing with proc.StandardError to get the error messages. You can spawn a background thread to synchronously read standard error alongside the reading of standard output in the main thread.

James Johnston
  • 9,264
  • 9
  • 48
  • 76
  • 1
    Forgot to mention, but this question may be useful to you as well: http://stackoverflow.com/questions/1369236/how-to-run-console-application-from-windows-service – James Johnston May 23 '11 at 16:24
  • This solution works find for cmd and other executables, but fails for powershell scripts. Any ideas on how to make it work for powershell too? – Micah May 23 '11 at 17:12
  • I think you'll need to find and execute the PowerShell executable directly, passing your script as an argument. You could test the path argument for a PowerShell extension and provide special handling. Setting UseShellExecute to true would allow execution of the PS script but does not allow for output redirection (as you've probably discovered). This seems to be a limitation of the Windows API so there's not much you can do. Redirection requires use of CreateProcess API, which requires an executable... – James Johnston May 23 '11 at 20:14
  • I figured it out. I was erroneously overwriting the output data before I displayed it =) Doh!! – Micah May 24 '11 at 12:32