Search code examples
powershelluntil-loop

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!


Solution

  • 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)