2016-04-26 91 views
8

這可能看起來像一個非常非常愚蠢的問題,但我不能真正弄清楚。我試圖讓函數停下來,當它發現它的第一個命中(匹配),然後繼續與腳本的其餘部分。退出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 

我使用breakexitcontinuereturn嘗試,但這些都不讓我期望的結果。感謝您的幫助。

回答

6

如上所述,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' 
+0

完美!這是第一個也是唯一可行的例子!謝謝安德烈:) – DarkLite1

+0

這似乎工作正常'foreach($(1..6)){break { – DarkLite1

0

您傳遞給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