1

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 :

  1. Launch the C# app
  2. Run PowerShell process in parallel
  3. [...] Do some other stuff [...]
  4. 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).

7
  • Target PowerShell version? Commented Mar 5, 2016 at 14:38
  • The last one: PowerShell 5.0 on Windows 10 Commented Mar 5, 2016 at 15:07
  • Create a Runspace when the application launches, then assign all subsequent System.Management.Automation.PowerShell instances you create from the text box input to that runspace. Commented Mar 5, 2016 at 15:54
  • @MathiasR.Jessen Thanks for your answer, does creating the runspace launch PowerShell in background? I thought it was done only after calling BeginInvoke() but if I'm wrong (so, if, creating the runspace launches PowerShell and BeginInvoke() runs scripts on the created process), it would be perfect. Can you tell me a little bit more about that? Commented Mar 5, 2016 at 16:15
  • @Gaël In-process Runspace does not create PowerShell process. It run PowerShell code inside your process. Commented Mar 5, 2016 at 16:19

1 Answer 1

5

As mentioned in the comments, set up (and open) a runspace when the application launches:

Runspace rs;
public MainWindow()
{
    InitializeComponent();
    rs = RunspaceFactory.CreateRunspace();
    rs.Open();
}

Now, all you need is a function that creates a PowerShell instance and executes it in the runspace:

private Collection<PSObject> RunScript(string script)
{
    using(PowerShell ps = PowerShell.Create())
    {
        ps.AddScript(script);
        ps.Runspace = rs;
        return ps.Invoke();
    }
}

And then, in your event handler for running the script input by the user:

private void button_Click(object sender, RoutedEventArgs e)
{
    Collection<PSObject> returnedObjects = RunScript(TextBox_Input.Text);
    // do what you want with returnedObjects if necessary
}

This is, of course, an overly simplified example. In a real world application you would inspect the error and warning streams, employ APM (BeginInvoke()/EndInvoke()) etc.

Sign up to request clarification or add additional context in comments.

3 Comments

And if someone really want to have separate PowerShell process, then (s)he need to change CreateRunspace() to CreateOutOfProcessRunspace(null).
@PetSerAl Correct, but from the comments it sounds like the "separate process" thing was a bit of an XY request
@MathiasR.Jessen I haven't tried to use Runspace and PowerShell like that, and... it works like a charm! Thank you for responding so quickly. And you're right, it was an XY request, my explanation wasn't very great, but, you found the solution after all!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.