Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to answer to Read-Host from C# code that invoked that PowerShell script?

Tags:

c#

powershell

I need to run PowerShell script from inside my C# code. That is easy. But then, my PowerShell script contains several Read-Host commands. Normally, the script execution would stop and the user should manually enter some value to PowerShell consoleas an answer. But what I need is to answer to these Read-Host requests from the same code in C# that executed and controls the flow of that script. In other words I need my script to stop at some point and await for some data input from my C# code, then get it and continue execution.

I found how to run PS from C#, I found how to pass arguments or initial variables from C# to PS script when launching it, but I can't find any way how to make my script await for some data from the host application, receive it and continue exectuion within host application, all these during runtime of script, not on its launch.

Can you please guide me to some direction fo search or code that might help?

like image 301
Konstantin Avatar asked Oct 21 '25 18:10

Konstantin


1 Answers

You can call WriteLine() on the StandardInput of the process. That will provide data for one Read-Host in the script.

To do so make sure UseShellExecute of the respective ProcessStartInfo is set to false and its RedirectStandardInput to true.

So for example

    Process p = Process.Start(new ProcessStartInfo()
    {
        FileName = "powershell",
        Arguments = @"C:\Users\Konstantin\ps.ps1",
        UseShellExecute = false,
        RedirectStandardInput = true,
    });

    p.StandardInput.WriteLine("abc");

will provide "abc" to the first Read-Host of the script C:\Users\Konstantin\ps.ps1.

If there are more Read-Hosts call WriteLine() again. Or you can use string concatenation with StandardInput.NewLine and just use Write. For example

p.StandardInput.Write("abc" + StandardInput.NewLine + "xyz" + StandardInput.NewLine);

will provide "abc" for the first and "xyz" for the second Read-Host.

like image 194
sticky bit Avatar answered Oct 24 '25 07:10

sticky bit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!