Nick W.
Nick W.

Reputation: 1614

Exit loop from function

I want to break the following loop from a function that was called kind of like shown below.

Function test {
    $i++
    IF ($i -eq 10) {continue}
}

$Computers = "13","12","11","10","9","8","7","6","5","4","3","2","1"
ForEach ($Computer in $Computers) {
    Test
    write-host "Fail"
}

Upvotes: 0

Views: 1062

Answers (2)

BellsAndWhistles
BellsAndWhistles

Reputation: 1

I tried, indeed you can.

Function Test ($i) {
    if ($i -eq 10) {continue}
    if ($i -eq 3)  {break}
}

$numbers = "13","12","11","10","9","8","7","6","5","4","3","2","1"
ForEach ($number in $numbers) {
    Test $number
    write-host "$number"
}

Output:

13
12
11
9
8
7
6
5
4

So, 10 is skipped, and it exited the loop on 3.

It's just coding like that is a bad practice, because it's generally not expected from a function to break loops.

Unless the function has a name related to loops. Like "Exit-LoopOnFailure()"

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126732

If I'm following you...

Function test {
    $args[0] -eq 10
}

$Computers = "13","12","11","10","9","8","7","6","5","4","3","2","1"
ForEach ($Computer in $Computers) {
    if(Test $Computer) {break} else {$Computer}
}

Upvotes: 3

Related Questions