I'm creating a C#/WPF app that needs to interact with PowerShell (basically, run commands and scripts). Creating the process and launching it is not a problem, that's pretty easy, but it becomes more difficult when the goal is to launch it without any script and make it run commands and scripts later :
- Launch the C# app
- Run PowerShell process in parallel
- [...] Do some other stuff [...]
- Run commands on the process
I tried multiple solutions.
With the System.Diagnostics.Process class, I am able to launch the process, let it run, but even if I redirect streams, writing to stdin just doesn't work:
var startInfo = new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = "-ExecutionPolicy Bypass -NoLogo -NoExit",
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden
};
_ps = new Process()
{
EnableRaisingEvents = true,
StartInfo = startInfo
};
_ps.Start();
[...]
_ps.StandardInput.WriteLine(TextBox_Input.Text); // No effect
Using System.Management.Automation.PowerShell class is not better, I can prepare the pipeline (add scripts to be executed), invoke it, but, I can't run scripts later keeping the process alive.
I need to launch the process as soon as possible to be able to send it commands and run them the faster I can (and avoid process launching that would cause a latency).
Runspacewhen the application launches, then assign all subsequentSystem.Management.Automation.PowerShellinstances you create from the text box input to that runspace.BeginInvoke()but if I'm wrong (so, if, creating the runspace launches PowerShell andBeginInvoke()runs scripts on the created process), it would be perfect. Can you tell me a little bit more about that?Runspacedoes not create PowerShell process. It run PowerShell code inside your process.