退出 PowerShell 函数但继续执行脚本

Exit a PowerShell function but continue the script

这似乎是一个非常非常愚蠢的问题,但我真的想不通。我试图让函数在找到第一次命中(匹配)时停止,然后继续执行脚本的其余部分。

代码:

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'

想要的结果:

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

我试过使用 breakexitcontinuereturn,但其中的 none 得到了我想要的结果。谢谢你的帮助。

您传递给 ForEach-Object 的脚本块本身就是一个函数。该脚本块中的 return 距脚本块的当前迭代仅 returns。

您需要一个标志来立即告诉 return 未来的迭代。类似于:

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

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

除此之外,您最好使用 Where-Object 将管道对象过滤为仅需要处理的对象。

如前所述,Foreach-object 是它自己的一个函数。使用常规 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'