Exit a PowerShell function but continue the script [duplicate] Exit a PowerShell function but continue the script [duplicate] powershell powershell

Exit a PowerShell function but continue the script [duplicate]


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 -VerboseWrite-Output 'The script continues here'


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.