简体   繁体   中英

powershell until loop not working as intended

the desired output would be to repeat the question until either "Y" or "N" is selected.

 $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 .

You can either use the -or operator:

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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