退出PowerShell功能,但继续脚本
问题描述:
这可能看起来像一个非常非常愚蠢的问题,但我不能真正弄清楚。我试图让函数停下来,当它发现它的第一个命中(匹配),然后继续与脚本的其余部分。退出PowerShell功能,但继续脚本
代码:
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
我使用break
,exit
,continue
和return
尝试,但这些都不让我期望的结果。感谢您的帮助。
答
如上所述,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'
答
您传递给ForEach-Object
的scriptblock本身就是一个函数。该脚本块中的return
仅从脚本块的当前迭代中返回。
您需要一个标志来告诉未来的迭代立即返回。喜欢的东西:
$done = $false;
1..6 | ForEach-Object {
if ($done) { return; }
if (condition) {
# We're done!
$done = $true;
}
}
而不是这样的,你可以使用Where-Object
到管道对象筛选,只有那些你需要处理更好。
+0
我正在尝试你的例子,但我无法让它工作。你可以使用我的和适应所以我可以看到结果?无论我做什么,它仍在迭代“Verbose”流中的其他数字 – DarkLite1
完美!这是第一个也是唯一可行的例子!谢谢安德烈:) – DarkLite1
这似乎工作正常'foreach($(1..6)){break { – DarkLite1