0

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"
}
1
  • what are you trying to do ? if you want to break, use the break keyword, not continue :) Commented Feb 3, 2013 at 7:53

2 Answers 2

3

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

1 Comment

yep thats what I am going for just wondering if I could call the break from inside the function so I can keep the main body of the script clean as possible.
0

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()"

Comments

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.