DarkLite1
DarkLite1

Reputation: 14745

Exit a PowerShell function but continue the script

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.

Upvotes: 21

Views: 59722

Answers (2)

Andrey Marchuk
Andrey Marchuk

Reputation: 13483

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'

Upvotes: 16

Richard
Richard

Reputation: 109140

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.

Upvotes: 3

Related Questions