简体   繁体   English

powershell until 循环无法按预期工作

[英]powershell until loop not working as intended

the desired output would be to repeat the question until either "Y" or "N" is selected.期望的输出是重复问题,直到选择“Y”或“N”。

 $msg = 'Does this Share contain Sensitive Data? [Y/N]'
do {
    $response = Read-Host -Prompt $msg
    if ($response -eq 'n') {
      $sdata = "No"

    }

 if ($response -eq 'y') {
        $sdata = "(Sensitive)"
      


        
    }


} until ($response -ne '$null')

However if I enter anything else it will still continue to run the script.但是,如果我输入其他任何内容,它仍然会继续运行脚本。 I have this working on other scripts so I am unsure of why its not working now.我有这个在其他脚本上工作,所以我不确定为什么它现在不工作。

Thanks as always!一如既往的感谢!

So you want to repeat the prompt until someone enters a valid value - either y or n .因此,您希望重复提示,直到有人输入有效值 - yn

You can either use the -or operator:您可以使用-or运算符:

do {
  # ...
} until ($response -eq 'y' -or $response -eq 'n')

Since you're testing the same variable for one of multiple possible values, you could also use the reverse containment operator -in to test if the input was part of the set of valid values:由于您正在为多个可能值之一测试相同的变量,因此您还可以使用反向包含运算符-in来测试输入是否是一组有效值的一部分:

do {
  # ...
} until ($response -in 'y','n')

... or, if you want a "cleaner" condition expression, use a variable to keep track of whether a valid value has been entered: ...或者,如果您想要一个“更干净”的条件表达式,请使用变量来跟踪是否输入了有效值:

$done = $false
do {
    $response = Read-Host -Prompt $msg
    
    if ($response -eq 'n') {
        $sdata = "No"
        $done = $true
    }

    if ($response -eq 'y') {
        $sdata = "(Sensitive)"
        $done = $true
    }

} until ($done)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM