PowerShell:为什么while()语句永远循环?

时间:2013-12-05 08:35:40

标签: powershell while-loop

为什么以下while语句永远循环?我想在用户输入“是”或“否”后突破。其他一切都应该让他留在输入循环中。

while ($input -ne "yes" -or $input -ne "no") {
    $input = Read-Host "Ready to process? [yes|no]"

    switch ($input) {
        yes { 
            write-host "yes"    
        }

        no  { 
            write-host "no" 
        }

        default { 
            write-host "input not understood" 

        }
    }  
}

3 个答案:

答案 0 :(得分:6)

让我们解开逻辑:

1)如果输入为“是”,那么它不等于“否”。

2)如果输入为“no”,则它不等于“yes”。

3)如果它既不是“是”也不是“否”,则它不等于“是”或“否”。

因此while ($input -ne "yes" -or $input -ne "no") {总是如此。所以它永远循环。

我认为你的意思是

while ($input -ne "yes" -and $input -ne "no") {

有趣的是,你在这里可以用德摩根的法律来表达。见http://en.wikipedia.org/wiki/De_Morgan%27s_laws

答案 1 :(得分:1)

因为你要求在$input不是“是”时循环或者不是“否”。

or的真实表:

 A    B       A -or B
 F    F   ->     F
 F    T   ->     T
 T    F   ->     T
 T    T   ->     T

想象一下输入是“是”,第二条件是true然后循环将继续。想象一下,现在输入是“否”,然后第一个条件是true,循环将再次继续。想象一下,现在输入是“可能”:两个条件都是真的,循环将继续。你的一个条件总是满足所以循环不会停止(真值表的2到4行)。此外,根据布尔逻辑,您知道!a and !b等于!(a or b)

 A    B        A or B    not A and not B    not (A or B)
 F    F   ->   F         T                  T
 F    T   ->   T         F                  F
 T    F   ->   T         F                  F
 T    T   ->   T         F                  F

您需要的运算符是and:如果输入不是“是”既不是“否”,则必须执行循环:

while ($input -ne "yes" -and $input -ne "no") {

表示:如果输入不是“是”,如果不是“否”,则再次询问

答案 2 :(得分:0)

这不是我的代码,但我也在寻找这个问题的答案 - 来自TechNet的jrv建议这款漂亮的单行程序,对我来说非常适合:

while(($ans=Read-Host 'Do you want to prepare the text (y / n)') -notmatch '^Y$|^N$'){}

自"而"做任何事情都在大括号内,它说"当输入不是Y或N时,什么都不做" (它只是无休止地重复这个问题 - 所以不需要默认"输入不被理解")。

希望这有帮助!

来源:

https://social.technet.microsoft.com/Forums/windowsserver/en-US/e93e9740-ef6c-49ab-bb53-b40ddcbeb0f4/validate-input-from-readhost-using-trycatch?forum=winserverpowershell#54e5b845-3ce0-4a75-9201-65f30689b717][1]