直到用户输入是/否

use*_*825 2 powershell

我试图写一个简单的do..until循环,它不起作用:

$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")
Run Code Online (Sandbox Code Playgroud)

这个只做了两次循环,但它应该每次我击中Y时循环,但是当我击中Nn它应该打破.

有任何想法吗?

Ans*_*ers 8

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

  • Read-Hostcmdlet的:

    $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')
    
    Run Code Online (Sandbox Code Playgroud)

    使用-like 'y*'-like 'n*'如果你想忽略响应尾随字符.

  • 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)
    
    Run Code Online (Sandbox Code Playgroud)
  • choice命令:

    $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)
    
    Run Code Online (Sandbox Code Playgroud)