best way to break out of foreach loop

This topic contains 4 replies, has 4 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 2 years, 1 month ago.

  • Author
    Posts
  • #19905
    Profile photo of michael glenn
    michael glenn
    Participant

    trying to find the best way to break out of a foreach loop.
    for instance... testing if a pc is on.. if its on.. performing various commands.. but if it isn't on.. just go on to the next pc in a list.
    suggestions?

  • #19907
    Profile photo of Ondrej Zilinec
    Ondrej Zilinec
    Participant

    Look HERE.

  • #19909
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    That depends on whether you're talking about the foreach keyword or the ForEach-Object cmdlet, when you say "foreach loop". Also, the word "break" has special meaning which doesn't correspond to the behavior you're describing. The commands you would use to move on to the next item in the loop would be either 'continue' (for the foreach keyword) or 'return' (for ForEach-Object):

    $numbers = 1..10
    
    foreach ($number in $numbers)
    {
        if ($number % 2 -eq 0)
        {
            continue
        }
    
        Write-Host "$number is odd."
    }
    
    # or:
    
    $numbers |
    ForEach-Object {
        if ($_ % 2 -eq 0)
        {
            return
        }
    
        Write-Host "$_ is odd."
    }
    

    It's important not to try to use the continue or break keywords from inside ForEach-Object; that's a bit of a PowerShell gotcha. It won't complain, but it'll start walking up the call stack looking for a loop (or switch statement) that can process the continue / break, and if it doesn't find one, it'll just abort your entire script.

  • #19912
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    I agree with Ondrej, there is no need to actually do a break\return in your 'for' logic. There are a LOT of examples on this, so some simple searches and you will find plenty of examples, but it will be something like

    $computers | foreach {
        if (Test-Connection $_ -Count 2 -Quiet) {
            #Connected, run other queries
        }
        else {
            #Not connect, log as offline
        }
    }
  • #19915
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Using break / continue keeps the level of indentation down throughout the rest of the loop body, which can be valuable in some circumstances (though these days, one would probably argue that if a loop has so much code that this matters, then you should be refactoring it into separate functions anyway.)

You must be logged in to reply to this topic.