【问题标题】:Problem with switch statement in a while loop in PowerShellPowerShell中while循环中的switch语句问题
【发布时间】:2019-02-19 08:07:00
【问题描述】:

无论出于何种原因,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."
        }
    }
}

【问题讨论】:

  • 这就是您的代码似乎要做的——[1] 获取输入 [2] 测试它是否不匹配 只有yn [ 3] 如果它没有通过测试 [yn 以外的任何东西],它将针对 yn !!!!!! [grin] ///// 您已经确定它不会包含其中任何一个...那么您为什么希望触发两个开关值中的任何一个?您需要包含一个 default 来处理不匹配项。 ///// 同样,try/catch 在那里什么也没做......你想用它做什么?
  • 嗯,它应该匹配 y (继续执行命令)或 n (结束脚本),而当 y 或 n 没有提供时,它应该保留在循环中。至于 try/catch,我最初有一些其他代码,但这没关系,因为它甚至不会输出简单的 Write-Output cmdlet。
  • 说真的,遵循您的代码逻辑。 [grin] 它永远不会到达switch,因为while 说“只有在既没有输入“n”也没有输入“y”的情况下运行循环代码。
  • 是的,有点奇怪。但是当我使用 -match 时,循环中断了。如果我输入 y 或 n,正确的块将被执行,但是当我输入其他内容时,它只会结束脚本。这不完全是一个循环。我最终使用了not -notmatch,如下图@Mudit Bahedia 所示,并通过在每个输出中添加return 进行了一些更改,否则循环不会结束。

标签: powershell while-loop switch-statement


【解决方案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!

【讨论】:

    【解决方案2】:

    您正在使用-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."
            }
        }
    }
    

    【讨论】:

    • 嗨,谢谢,我试过了。最初它执行 y 或 n 块,但不会结束脚本,一旦我输入 y 或 n,它将继续循环。然后我想我只是在 Success、Error、Canceled 输出之后添加break,但这不起作用。原来它是return 我正在寻找的东西。现在它似乎按预期工作了。
    猜你喜欢
    • 1970-01-01
    • 2013-12-20
    • 2013-04-13
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多