1

I am attempting to run a PS script from C# with Powershell as a Process, like this:

 ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName =   configFile.AppSettings.Settings["PSDir"].Value.ToString() + @"\powershell.exe";
        startInfo.Arguments = @"& '" + scriptPath + "'\"";
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;
        startInfo.UseShellExecute = false;
        startInfo.CreateNoWindow = true;

        Process process = new Process();
        process.StartInfo = startInfo;            
        process.Start();

        return process;

I call that method like this:

        Process proc = RunPSScript(startupPath + "\\stats.ps1");
        proc.WaitForExit();

The program gets stuck at:

proc.WaitForExit();

I can tell the initial part of the script completes but nothing beyond that. It is not the script that is bad because I have run it outside of the code and it runs perfectly fine.

When I remove the WaitForExit(), the process call exists right away and the program keeps going, but that's no good because I need to have the script generate data before the rest of the program can keep going.

Curiously, if I end the debug session after having started the PS call, the script keeps running and whatever was locking up its completion is now gone and it continues running to completion.

Any ideas appreciated.

Thanks!

A.G.
  • 2,089
  • 3
  • 30
  • 52
  • You may need to read from the output streams of the process before the process will exit. – Mark W Nov 03 '15 at 21:46
  • 1
    To add onto Mark W's comment: http://stackoverflow.com/questions/26713373/process-waitforexit-doesnt-return-even-though-process-hasexited-is-true – Marco Fatica Nov 03 '15 at 21:47
  • up'ed for the link... Definitely a dupe. – Mark W Nov 03 '15 at 21:50
  • AARrrgghh, the problem is this line: startInfo.Arguments = @"& '" + scriptPath + "'\""; Need to remove \" , now it works. Silly me! – A.G. Nov 03 '15 at 21:52

1 Answers1

0

2 things to check, what is the exact output of your arguments? Given that run the same script from CMD prompt as admin and see if it has the same result. You can also pass in a timeout to the wait for exit in Milliseconds. Try this:

RunPSScript(startupPath + "\\stats.ps1").WaitForExit();
Kentonbmax
  • 938
  • 1
  • 10
  • 16