停止PowerShell管道,确保调用end

cam*_*.rw 11 powershell pipeline powershell-4.0

我要做的是获得一个函数来在达到时间限制时停止管道输入.我创建了一个测试函数如下:

function Test-PipelineStuff
{
    [cmdletbinding()]
    Param(
        [Parameter(ValueFromPipeLIne=$true)][int]$Foo,
        [Parameter(ValueFromPipeLIne=$true)][int]$MaxMins
    )

    begin { 
        "THE START" 
        $StartTime = Get-Date
        $StopTime = (get-date).AddMinutes($MaxMins)
        "Stop time is: $StopTime"
    } 

    process 
    {  
        $currTime = Get-Date
        if( $currTime -lt $StopTime ){
            "Processing $Foo"            
        }
        else{
            continue;
        }
    }

    end { "THE END" }
}
Run Code Online (Sandbox Code Playgroud)

这肯定会阻止管道,但它永远不会调用我的"end {}"块,在这种情况下它是至关重要的.有没有人知道为什么当我使用"继续"停止管道时,我的"end {}"块没有被调用?如果我抛出PipelineStoppedException,行为似乎是相同的.

Flo*_*aus 2

根据about_Functions

函数接收到管道中的所有对象后,End 语句列表会运行一次。如果未使用 Begin、Process 或 End 关键字,则所有语句都将被视为 End 语句列表。

因此你只需要省略该else块即可。然后,管道中的所有对象都会被处理,但由于该if子句,实际处理只会在达到时间限制之前完成。

  • 不,问题是如何停止管道并确保调用结束。 (2认同)