【问题标题】:Exit a PowerShell function but continue the script退出 PowerShell 函数但继续执行脚本
【发布时间】:2016-08-19 21:46:47
【问题描述】:

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

代码:

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,但这些都没有让我得到想要的结果。感谢您的帮助。

【问题讨论】:

  • 这不是重复的。它询问如何退出函数,而不是如何退出循环。

标签: function powershell exit


【解决方案1】:

如前所述,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'

【讨论】:

    【解决方案2】:

    您传递给ForEach-Object 的脚本块本身就是一个函数。该脚本块中的return 只是从脚本块的当前迭代返回。

    您需要一个标志来告诉未来的迭代立即返回。比如:

    $done = $false;
    1..6 | ForEach-Object {
      if ($done) { return; }
    
      if (condition) {
        # We're done!
        $done = $true;
      }
    }
    

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

    【讨论】:

    • 我正在尝试您的示例,但无法正常工作。您可以使用我的并进行调整,以便我可以看到结果吗?无论我做什么,它仍在迭代 Verbose 流中的其他数字
    猜你喜欢
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2017-10-31
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多