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

问题描述 投票:0回答:2

无论出于何种原因,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."
        }
    }
}
powershell while-loop switch-statement
2个回答
0
投票

您正在使用-notmatch。因此While循环导致false并且循环没有被执行。由于你想要执行脚本直到你输入'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."
        }
    }
}

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!
© www.soinside.com 2019 - 2024. All rights reserved.