直到用户输入是/否 [英] do until user input yes/no

查看:47
本文介绍了直到用户输入是/否的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的 do..until 循环,但它不起作用:

I am trying to write a simple do..until loop and it does not work:

$yesNo = Read-Host -Prompt 'Do you want to add alternative DNS names or IPs into Certificate? Y/N: '

do {
    $dnsipname = Read-Host -Prompt "Please input DNS or IP as dns=alternativeCNname or ip=ipName: "
    Write-Output "$dnsipname" 
    $strQuit = Read-Host " do you want to add another DNS? (Y/N)"
    do {
        $dnsipname = Read-Host -Prompt "Please input DNS or IP as dns=alternativeCNname or ip=ipName: "
        Write-Output "$dnsipname" 
        Add-Content D:\Scripts\expiringCerts\request.inf '`r`n_continue_ = "$dnsipname"'
    } until ($strQuit -eq "Y" -or "y")
} until ($yesNo -eq "Y" -or "y")

这个只循环两次,但每次我点击 Y 时它都应该循环,但是当我点击 Nn 时它应该会中断.

This one does loop twice only, but it should loop every time I hit Y but when I hit N or n It should break.

有什么想法吗?

推荐答案

在 PowerShell 中,您基本上有三个选项来提示用户选择是/否.

In PowerShell you have basically three options to prompt a user for a yes/no choice.

  • The Read-Host cmdlet:

$msg = 'Do you want to add alternative DNS names or IPs into Certificate? [Y/N]'
do {
    $response = Read-Host -Prompt $msg
    if ($response -eq 'y') {
        # prompt for name/address and add to certificate
    }
} until ($response -eq 'n')

如果您想忽略响应中的尾随字符,请使用 -like 'y*'-like 'n*'.

Use -like 'y*' and -like 'n*' if you want to ignore trailing characters in the response.

PromptForChoice() 方法:

$title   = 'Certificate Alternative Names'
$msg     = 'Do you want to add alternative DNS names or IPs?'
$options = '&Yes', '&No'
$default = 1  # 0=Yes, 1=No

do {
    $response = $Host.UI.PromptForChoice($title, $msg, $options, $default)
    if ($response -eq 0) {
        # prompt for name/address and add to certificate
    }
} until ($response -eq 1)

  • 选择 命令:

    $msg = 'Do you want to add alternative DNS names or IPs into Certificate'
    do {
        choice /c yn /m $msg
        $response = $LASTEXITCODE
        if ($response -eq 0) {
            # prompt for name/address and add to certificate
        }
    } until ($response -eq 1)
    

  • 这篇关于直到用户输入是/否的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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