Automate PowerShell Response to prompt

╄→гoц情女王★ 提交于 2021-02-08 08:29:41

问题


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:


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.


来源:https://stackoverflow.com/questions/53330644/automate-powershell-response-to-prompt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!