Running PowerShell using System.Diagnostics.Process and Redirected I/O

Hi,

I am having difficulty running PowerShell (4.0, 5.1) from a host .net application using the System.Diagnostics.Process class.

Specially when using the “-Command -” option with redirected I/O.

The main issue is I can’t get PowerShell to exit after running commands.

As a secondary issue I am having trouble getting the output as commands are executed.

For example, I can use cmd.exe from a Process object and send commands and get back the results in an interactive manor. PowerShell seems to send the output from the first set of commands received and the rest appears to be buffered.

 

My objective is to be able to open PowerShell from the .Net Host and execute commands in a request-response pattern. I have tried flushing the buffer streams in the Process object but to no avail!.

For example:

  1. open PowerShell with using Process and redirected I/O using command line: -NoLogo - NoExit -NoProfile -NonInteractive -Command -
    1. please note: the use of "-NonInteractive" doesn't seem to make a difference
  2. run the following command 10x: Get-Process | ConvertTo-Csv
  3. Generally the first command returns a response
  4. I can't get PowerShell to close using: exit, [Environment]::Exit(0)
While I am looking into using the SDK the scope of my current project is to use the Process class.

 

Thanks in advance for your time and consideration!

April