Is it possible to terminate or stop a PowerShell pipeline from within a filter

后端 未结 8 2162
無奈伤痛
無奈伤痛 2020-12-06 06:27

I have written a simple PowerShell filter that pushes the current object down the pipeline if its date is between the specified begin and end date. The objects coming down

8条回答
  •  北海茫月
    2020-12-06 06:50

    It is possible to break a pipeline with anything that would otherwise break an outside loop or halt script execution altogether (like throwing an exception). The solution then is to wrap the pipeline in a loop that you can break if you need to stop the pipeline. For example, the below code will return the first item from the pipeline and then break the pipeline by breaking the outside do-while loop:

    do {
        Get-ChildItem|% { $_;break }
    } while ($false)
    

    This functionality can be wrapped into a function like this, where the last line accomplishes the same thing as above:

    function Breakable-Pipeline([ScriptBlock]$ScriptBlock) {
        do {
            . $ScriptBlock
        } while ($false)
    }
    
    Breakable-Pipeline { Get-ChildItem|% { $_;break } }
    

提交回复
热议问题