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.

1
  • 1
    This is not a duplicate. It asks how to exit a function, not how to exit a loop. Commented Nov 17, 2021 at 17:13

2 Answers 2

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

Comments

4

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.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.