這可能看起來像一個非常非常愚蠢的問題,但我不能真正弄清楚。我試圖讓函數停下來,當它發現它的第一個命中(匹配),然後繼續與腳本的其餘部分。退出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
嘗試,但這些都不讓我期望的結果。感謝您的幫助。
完美!這是第一個也是唯一可行的例子!謝謝安德烈:) – DarkLite1
這似乎工作正常'foreach($(1..6)){break { – DarkLite1