Home > OS >  Interrupting a loop
Interrupting a loop

Time:07-20

I just do my first steps with powershell and have a questions about a loop I'm using in a script:

for ($i=1; $i -le 100; $i  ){
    $res = Test-Connection $IP -count 1 -Quiet
    ...do something more
    start-sleep -seconds 30
}

This script does not allow to close the windows form (it's started from a GUI) or interrupt the loop. Is there a way to do so? Sometimes I want to stop the loop manually.

Thanks a lot for your help.

CodePudding user response:

I think you might want to use powershell flow control. With powershell flow control you are able to manually control loops in powershell. Let me give you an example:

for ($i=1; $i -le 100; $i  ){
    $res = Test-Connection $IP -count 1 -Quiet
    ...do something more

    if ($res -eq $anyresultyouwouldexpect) {
       break ##with **break** you interupt the loop completely- You script 
             ## would continue after the loop.
    }
    

}

There are also flow control statements like continue to jump into the next iteration loop. It is depending on what you need in your case.

  • Related