退出PowerShell函数但继续脚本

Dar*_*te1 16 powershell function exit

这似乎是一个非常非常愚蠢的问题,但我无法弄明白.我试图让函数在找到第一个匹配(匹配)时停止,然后继续执行脚本的其余部分.

码:

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'
Run Code Online (Sandbox Code Playgroud)

期望的结果:

VERBOSE: 1
VERBOSE: 2
VERBOSE: 3
We found it
The script continues here
Run Code Online (Sandbox Code Playgroud)

我已经尝试使用break,exit,continuereturn,但这些都不让我期望的结果.谢谢您的帮助.

And*_*huk 10

如上所述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'
Run Code Online (Sandbox Code Playgroud)