Hello,
I am trying to run a PowerShell script from C# (I have no control over what's in the script). The script may have a prompt like "Press enter to continue". So my goal is:
1. Get text output from the script (easy, many examples available)
3. If output contains "Press enter to continue", write a blank line to the running script's pipe to make it finish its job and quit
4. If output does contain that prompt, just let it exit by itself without sending any input
Note that commands in this PS script also try to get at script's file path, so I can't read script from file and pass it as text. It has to be executed as a script so it knows where it's located.
I have done this with .exes and batch files before. All you do in that case is process.StandardInput.WriteLine() which "types" enter into the input stream of script you are trying to control. But this does not work with Power Shell. How do I do this?
I have tried using PS object model like so:
using (Pipeline pipeline = runspace.CreatePipeline())
{
Command command = new Command(scriptPS, true, true); pipeline.Commands.Add(command); pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); pipeline.Input.Write("\n"); Collection<PSObject> psresults = pipeline.Invoke();
//...
But I get an error because the script prompts:
"A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related
commands from command types that do not support user interaction, such as Windows PowerShell workflows."
I also tried using Process, and running PowerShell with -File switch to execute the script, then write to StandardInput with C#. I get no errors then, but the input is ignored and doesn't make it to PowerShell.
Please help!