21

This might seem like a very very stupid question, but I can't really figure it out. I'm trying to have the function stop when it finds its first hit (match) and then continue with the rest of the script.

Code:

Function Get-Foo {
    [CmdLetBinding()]
    Param ()

    1..6 | ForEach-Object {
        Write-Verbose $_
        if ($_ -eq 3) {
            Write-Output 'We found it'

            # break : Stops the execution of the function but doesn't execute the rest of the script
            # exit : Same as break
            # continue : Same as break
            # return : Executes the complete loop and the rest of the script
        }
        elseif ($_ -eq 5) {
            Write-Output 'We found it'
        }
    }
}

Get-Foo -Verbose

Write-Output 'The script continues here'

Desired result:

VERBOSE: 1
VERBOSE: 2
VERBOSE: 3
We found it
The script continues here

I've tried using break, exit, continue and return but none of these get me the desired result. Thank you for your help.

DarkLite1
  • 13,637
  • 40
  • 117
  • 214

2 Answers2

16

As was mentioned, Foreach-object is a function of its own. Use regular foreach

Function Get-Foo {
[CmdLetBinding()]
Param ()

$a = 1..6 
foreach($b in $a)
{
    Write-Verbose $b
    if ($b -eq 3) {
        Write-Output 'We found it'
        break
    }
    elseif ($b -eq 5) {
        Write-Output 'We found it'
    }
  }
}

Get-Foo -Verbose

Write-Output 'The script continues here'
Andrey Marchuk
  • 13,301
  • 2
  • 36
  • 52
3

The scriptblock you are passing to ForEach-Object is a function in its own right. A return in that script block just returns from the current iteration of the scriptblock.

You'll need a flag to tell future iterations to return immediately. Something like:

$done = $false;
1..6 | ForEach-Object {
  if ($done) { return; }

  if (condition) {
    # We're done!
    $done = $true;
  }
}

Rather than this, you may be better using a Where-Object to filter the pipeline objects to only those that you need to process.

Richard
  • 106,783
  • 21
  • 203
  • 265
  • I'm trying out your example, but I can't get it to work. Can you use mine and adapt so I can see the result? Whatever I do it's still iterating over the other numbers in the `Verbose` stream – DarkLite1 Apr 26 '16 at 08:07