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!