Automate PowerShell Response to prompt

2.8k views Asked by At

Creating a PowerShell script that calls an apps cmdlet. When then cmdlet runs it prompts for a response and the scripts hangs. The cmdlet doesn't have any parameters for this. Is there any way to respond programmatically? I tried ECHO but that doesn't work.

script hanging

1

There are 1 answers

0
mklement0 On

The only way to get PowerShell scripts that solicit input via the host - typically, via Read-Host - to read input from the pipeline instead of from the keyboard is to use to run the script as an external PowerShell instance.

A simple example:

# Does NOT work: pipeline input is IGNORED and Read-Host "hangs", i.e.,
# it waits for interactive input.
'y' | & { Read-Host "Y/N?" }


# OK: By launching the command via a new PowerShell instance,
#     Read-Host reads from the pipeline (stdin).
#     To run a script file externally, use -file instead of -command.
'y' | powershell -noprofile -command 'Read-Host "Y/N?"'

Note: Running the script / command via an external PowerShell instance comes at a cost:

  • Creating a new PowerShell process is costly in terms of performance.

  • Output from the new instance will be textual (strings) by default, not objects.

    • You can approximate the usual in-process experience by passing -OutputFormat xml to the external instance and post-processing the results via Import-CliXml, but that has limitations.