如何在 PowerShell 中使用 -confirm [英] How to Use -confirm in PowerShell

查看:144
本文介绍了如何在 PowerShell 中使用 -confirm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试接受用户输入,在继续之前,我希望在屏幕上收到一条消息而不是确认,无论用户是否想要继续.我正在使用以下代码,但它不起作用:

I'm trying to take user input and before proceeding I would like get a message on screen and than a confirmation, whether user wants to proceed or not. I'm using the following code but its not working:

write-host "Are you Sure You Want To Proceed:"  -Confirm

推荐答案

-Confirm 是大多数 PowerShell cmdlet 中的一个开关,它强制 cmdlet 要求用户确认.您实际要寻找的是 Read-Host cmdlet:

-Confirm is a switch in most PowerShell cmdlets that forces the cmdlet to ask for user confirmation. What you're actually looking for is the Read-Host cmdlet:

$confirmation = Read-Host "Are you Sure You Want To Proceed:"
if ($confirmation -eq 'y') {
    # proceed
}

PromptForChoice() 主机用户界面的方法:

or the PromptForChoice() method of the host user interface:

$title    = 'something'
$question = 'Are you sure you want to proceed?'

$choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))

$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
    Write-Host 'confirmed'
} else {
    Write-Host 'cancelled'
}

<小时>

正如 M-pixel 在评论中指出的,代码可以进一步简化,因为选项可以作为简单的字符串数组传递.

As M-pixel pointed out in the comments the code could be simplified further, because the choices can be passed as a simple string array.

$title    = 'something'
$question = 'Are you sure you want to proceed?'
$choices  = '&Yes', '&No'

$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
    Write-Host 'confirmed'
} else {
    Write-Host 'cancelled'
}

这篇关于如何在 PowerShell 中使用 -confirm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆