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

标签 function powershell 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'

期望的结果:

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

我尝试过使用 breakexitcontinuereturn 但这些都没有让我期望的结果。感谢您的帮助。

最佳答案

正如前面提到的,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'

关于function - 退出 PowerShell 函数但继续执行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36858588/

相关文章:

docker - 如何知道 docker 容器退出的原因?

c++ - 从 C++ 中的函数返回指向数组的指针?

ios - swift中的延迟函数

类似 Javascript C# 的函数表达式

java - System.exit(1) 在多线程程序中存在,返回码为 0

python - 当被调用的模块/程序发出 sys.exit() 时如何保护 python 解释器不被终止

r - R中函数的运算符重载 - 奇怪的行为

powershell - 将测试连接转换为 bool 值

powershell - 如何从 PowerShell 以编程方式列出 VSTS 代理池?

powershell - 在 IIS7.5 中使用 Powershell 设置启用父路径