1

Working on a project. In the code, we need to run powershell script and then get its output. In order to do this, I use the Process():

    private int RunProcess(string FileName, string Arguments, out string result)
    {
        int exitCode = -1;
        result = string.Empty;
        // Start the child process.
        Process p = new Process();
        // Redirect the output stream of the child process.
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = FileName;
        p.StartInfo.Arguments = Arguments;
        p.Start();
        // Do not wait for the child process to exit before
        // reading to the end of its redirected stream.
        // Read the output stream first and then wait.
        result = p.StandardOutput.ReadToEnd();
        // Wait at most 10 minutes
        p.WaitForExit(10 * 60 * 1000);
        exitCode = p.ExitCode;
        return exitCode;
    }

and call it like this:

    RunProcess("Powershell.exe", arguments, out sPSResult);

This works fine on most computers. However, on some, for some unknow reason, the RunProcess() never return, even we use p.WaitForExit(10 * 60 * 1000) .

Anyone knows why? or see this before? Is it because somewhere is blocked in the windows even WaitForExit is used?

Thanks

urlreader
  • 6,319
  • 7
  • 57
  • 91
  • You can also collect StandardError using "result = p.StandardError.ReadToEnd();" There might be some additional information there. What all is the script doing? – John Bartels Dec 22 '15 at 22:42

1 Answers1

0

Are you sure your code even reaches WaitForExit and is not hanging on ReadToEnd? My guess it's getting stuck there because it can't read all of the output. Also for details on how to deal with reading standard and error outputs from child processes correctly, see:

ProcessStartInfo hanging on "WaitForExit"? Why?

Community
  • 1
  • 1
Slava Asipenko
  • 392
  • 1
  • 3