【问题标题】:How do I ask for confirmation? [duplicate]我如何要求确认? [复制]
【发布时间】:2019-10-02 22:54:10
【问题描述】:

我想创建一个确认框。我想要一个弹出框,显示这似乎是工厂密钥。你想继续吗?如果是,则继续执行脚本的其余部分,如果不是,则退出脚本。

以下是我的脚本:

if (Test-Path $USB2\sources\install3.swm) { 
    $caption = "*** IT APPEARS THIS IS A FACTORY KEY ***"    
    $message = "Are you Sure You Want To Proceed:"
    [int]$defaultChoice = 1
    $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "I understand, flash over it."
    $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No"
    $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
    $choiceRTN = $host.UI.PromptForChoice($caption, $message, $options, $defaultChoice)

    if ( $choiceRTN -ne 1 ) {
        "Your Choice was Yes"
    } else {
        Stop-Process -Id $PID
    }
}

见位,$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)。我被卡住的地方是“你的选择是肯定的”,我不需要那个......如果是的话,我只需要它来继续脚本。我该怎么做?

【问题讨论】:

标签: powershell


【解决方案1】:

考虑使用System.Windows.MessageBox...

Add-Type -AssemblyName PresentationFramework
[System.Windows.MessageBox]::Show('It appears that this is the factory key. Do you wish to continue?', 'Confirmation', 'YesNo');

对于您的用例,

# You need this to use System.Windows.MessageBox
Add-Type -AssemblyName 'PresentationFramework'

# By default, you're blasting the USB drive
$continue = 'Yes'

# If you see the file, prompt the user
if ( $(Test-Path -Path "${USB2}\sources\install3.swm") ) { 
    $caption = "*** IT APPEARS THIS IS A FACTORY KEY ***"    
    $message = "Are you Sure You Want To Proceed:"

    $continue = [System.Windows.MessageBox]::Show($message, $caption, 'YesNo');
}

if ($continue -eq 'Yes') {
    # The user either (a) said "yes" to the "do you prompt" or
    # (b) the file didn't exist.

    Write-Output "Flash over..."
    # ...do the flashing here...
} else {
    # The user said "no" to the flash prompt

    Write-Output "Terminating process..."
    Start-Sleep 1
}

消息框将返回YesNo,您可以在控制流中使用它来确定后续步骤。如果这包括关闭窗口,请致电exit

【讨论】:

  • 看起来棒极了!正是我想做的。对于 if $continue -eq 'Yes' 的问题(我也将自己尝试...)...您是否将整个脚本的其余部分放在 {} 中?
  • 是的,这就是我认为你会做的事情。
  • 标记为答案?
  • 我真的很接近标记为答案。但是到目前为止,将其余代码放在 {} 中不起作用......仍在找出原因。感谢您询问 Rudy2015。
  • 实际上,我确实将其标记为答案。我认为这就是答案......我认为我只是错误地实施了它。谢谢=)
【解决方案2】:

以下提示输入,将点击的值存储在变量中,并将其作为字符串返回。检查$var 的值并从那里开始应该很简单。

$var = [System.Windows.MessageBox]::Show('It appears this is a factory key. Do you wish to continue?','DialogTitle','YesNoCancel','Warning')
echo("The value of the dialog box is $($var)")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2018-08-05
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多