如何自动运行提示UI选择的PowerShell脚本?

Sas*_*vic 1 powershell scripting

我有一个看起来像这样的powershell脚本p1.ps1(不完全是,但这可以作为一个例子):

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Do the action."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Exit."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice($title, $message, $options, 1)
Run Code Online (Sandbox Code Playgroud)

如何编写另一个脚本p2.ps1,它将运行第一个脚本(p1.ps1)并为其提供答案,以便p2.ps1执行时不会问任何问题?

我试过了:

echo y | p1.ps1
Run Code Online (Sandbox Code Playgroud)

但它没有做到这一点.

Ans*_*ers 9

$host.ui.PromptForChoice()正在与主机交互,而不是与管道的输出流交互.我不知道自动化主机提示的方法.

更清洁的解决方案是添加一个-Force开关p1.ps1:

[CmdletBinding()]
Param(
  [switch]$Force = $false
)
Run Code Online (Sandbox Code Playgroud)

并使该开关覆盖提示:

if (-not $Force) {
  $yes = New-Object System.Management.Automation.Host.ChoiceDescription ...
  $no  = New-Object System.Management.Automation.Host.ChoiceDescription ...
  $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
  $result = $host.ui.PromptForChoice($title, $message, $options, 1)
} else {
  $result = 0
}
Run Code Online (Sandbox Code Playgroud)

这样,当你像这样运行脚本时,不会显示提示:

./p1.ps1 -Force
Run Code Online (Sandbox Code Playgroud)