Home > Net >  Powershell - for loop with multiple conditions
Powershell - for loop with multiple conditions

Time:03-18

im trying to have a for loop which ends after 1 of 2 conditions is fullfilled.

I dont know what i am missing but with "-or" between these 2 conditions only one condition seems to be "working" i guess. Should the following for-loop not also quit after the value of $i is 3??

Here the code:

$test = "test"
$expected = "successful"
for($i = 0; ($i -lt 3) -or ($test -ne $expected); ($i  ) -and (sleep 1)){
    if($i -eq 5){
        $test = $expected
    }
    $test
    $i
}

and here is my output:

test 0 test 1 test 2 test 3 test 4 successful 5

CodePudding user response:

Should the following for-loop not also quit after the value of $i is 3?

Why should it? ($test -ne $expected) is still $true, and you've instructed PowerShell to continue the loop as long as either ($i -lt 3) or ($test -ne $expected) are true.

Change the loop condition to use the -and operator instead:

for($i = 0; ($i -lt 3) -and ($test -ne $expected); ($i  ) -and (sleep 1))

Assuming you want the sleep 1 statement to execute regardless of the value of $i, change the last part to not use -and too:

for($i = 0; ($i -lt 3) -and ($test -ne $expected); ($i  ;sleep 1)){
  • Related