0

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

1
  • 1
    -or makes the loop continue as longer as either condition is satisfied, change the -or to an -and. Commented Mar 18, 2022 at 9:22

1 Answer 1

3

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)){
Sign up to request clarification or add additional context in comments.

1 Comment

I think it would need $(..) for the second example: $($i++;sleep 1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.