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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With