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

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


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 } }


It is not possible to stop an upstream command from a downstream command.. it will continue to filter out objects that do not match your criteria, but the first command will process everything it was set to process.

The workaround will be to do more filtering on the upstream cmdlet or function/filter. Working with log files makes it a bit more comoplicated, but perhaps using Select-String and a regular expression to filter out the undesired dates might work for you.

Unless you know how many lines you want to take and from where, the whole file will be read to check for the pattern.


You can throw an exception when ending the pipeline.

gc demo.txt -ReadCount 1 | %{$num=0}{$num++; if($num -eq 5){throw "terminated pipeline!"}else{write-host $_}}

or

Look at this post about how to terminate a pipeline: https://web.archive.org/web/20160829015320/http://powershell.com/cs/blogs/tobias/archive/2010/01/01/cancelling-a-pipeline.aspx