PowerShell中while循环中的switch语句问题

时间:2019-02-19 08:07:00

标签: powershell while-loop switch-statement

无论出于何种原因,While循环本身都会起作用,当我将它们组合在一起时,Switch语句也会自动起作用。.While循环可以正常工作,但是Switch语句..不是很多。

y或n只是While循环接受的值,问题是当我给它y或n时,没有代码被执行,脚本就结束了。

PowerShell版本是5.1。

While (($UserInput = Read-Host -Prompt "Are you sure? (y/n)") -notmatch '^n$|^y$') {
    Switch ($UserInput) {
        'y' {
            Try {
                Write-Output "Success."
        }
            Catch {
                Write-Output "Error."
            }
        }
        'n' {
            Write-Output "Cancelled."
        }
    }
}

2 个答案:

答案 0 :(得分:1)

这是一种相当健壮的方法来执行您想要的操作。它设置有效的选择,请求输入,检测到无效的输入,对此进行警告,显示“成功”或“失败”消息-所有这些都没有复杂的逻辑。 [咧嘴]

$Choice = ''
$ValidChoiceList = @(
    'n'
    'y'
    )

while ([string]::IsNullOrEmpty($Choice))
    {
    $Choice = Read-Host 'Are you sure? [n/y] '
    if ($Choice -notin $ValidChoiceList)
        {
        [console]::Beep(1000, 300)
        Write-Warning ('Your choice [ {0} ] is not valid.' -f $Choice)
        Write-Warning '    Please try again & choose "n" or "y".'

        $Choice = ''
        pause
        }
    switch ($Choice)
        {
        'y' {Write-Host 'Success!'; break}
        'n' {Write-Warning '    Failure!'; break}
        }
    }

屏幕输出...

Are you sure? [n/y] : t
WARNING: Your choice [ t ] is not valid.
WARNING:     Please try again & choose "n" or "y".
Press Enter to continue...: 
Are you sure? [n/y] : y
Success!

答案 1 :(得分:0)

您正在使用-notmatch。因此While循环会导致错误,并且不会执行循环。由于要执行脚本直到获得“ y”或“ n”作为输入,只需使用!即可执行脚本,直到接收到“ y”或“ n”作为输入为止。 使用以下代码:

While (!($UserInput = Read-Host -Prompt "Are you sure? (y/n)") -notmatch '^n$|^y$') {
Switch ($UserInput) {
    'y' {
        Try {
            Write-Output "Success."
    }
        Catch {
            Write-Output "Error."
        }
    }
    'n' {
        Write-Output "Cancelled."
        }
    }
}