Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell – for loop with multiple conditions

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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

>Solution :

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)){
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading