0

I want to run multiple commands on the same powershell session/process using C#. (I can run them together successfully, but I'm trying to run them separately because I want to add commands to this session with the click of a button).

Here is the code I have:

        ProcessStartInfo startInfo = new ProcessStartInfo("powershell.exe");
        startInfo.RedirectStandardInput = true;
        //startInfo.Arguments = "echo helloworld";
        startInfo.RedirectStandardOutput = true;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.CreateNoWindow = true;
        startInfo.UseShellExecute = false;

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

        // Send the first PowerShell command to the process
        process.StandardInput.WriteLine("echo helloworld");

        // Read the output of the PowerShell process
        string output = process.StandardOutput.ReadToEnd();
        MessageBox.Show("output1: " + output);

        // Later, send another PowerShell command to the same process
        process.StandardInput.WriteLine("Get-Service");

        // Read the output of the PowerShell process again
        string output2 = process.StandardOutput.ReadToEnd();
        MessageBox.Show("output2: " + output);

        process.WaitForExit();

Every time it hits the "output = process.StandardOutput.ReadToEnd(); line, the code hangs up. Is this because the process never ends?

There is a line I commented out at the top, where I give it an Argument. If I disabled RedirectStandardInput and instead fed it an argument, this DOES work. But I can't get it working with the standardInput.

Does anyone have a solution for this?

Thank you!

ASh
  • 34,632
  • 9
  • 60
  • 82
  • 1
    What you'd like to achieve isn't possible using System.Diagnostics.Process. – Tu deschizi eu inchid Mar 17 '23 at 22:04
  • 2
    The following may be of interest: https://stackoverflow.com/a/58211901/10024425. [PowerShell Class](https://learn.microsoft.com/en-us/dotnet/api/System.Management.Automation.PowerShell?view=powershellsdk-7.2.0), [System.Management.Automation.Runspaces Namespace](https://learn.microsoft.com/en-us/dotnet/api/System.Management.Automation.Runspaces?view=powershellsdk-7.2.0) – Tu deschizi eu inchid Mar 17 '23 at 22:15
  • 1
    `.ReadToEnd()` presumably waits until stdout is _closed_, which doesn't happen until the PowerShell process _exits_. While there may be a (brittle) way to make this work, it will be cumbersome, and you'll be much better off using the [PowerShell SDK](https://learn.microsoft.com/en-us/powershell/scripting/developer/hosting/adding-and-invoking-commands). – mklement0 Mar 17 '23 at 23:11

0 Answers0