best way to break out of foreach loop

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.

Look HERE.

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)

    Write-Host "$number is odd."

# or:

$numbers |
ForEach-Object {
    if ($_ % 2 -eq 0)

    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.

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

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.)