Aborting Pipeline

by May 19, 2015

Sometimes you might want to abort a pipeline when a certain condition is met.

Here is a creative way of doing this. It works all the way back to PowerShell 2.0.

Take a look at the sample code:

filter Stop-Pipeline 
{
     param
     (
         [scriptblock]
         $condition = {$true}
     )

     
     if (& $condition) 
     {
       continue
     }
     $_
}

do {
    Get-ChildItem c:\Windows -Recurse -ErrorAction SilentlyContinue | Stop-Pipeline { ($_.FullName.ToCharArray() -eq '\').Count -gt 3 } 
} while ($false)

The pipeline recursively scans the Windows folder. There is a new command called Stop-Pipeline. You can assign it a script block, and if this script block evaluates to $true, the pipeline is aborted.

In this example, you control the recursion depth. Once there are more than three backslashes in a path, the pipeline stops. Increase the number "3" to a higher number in order to recurse deeper into a folder.

The trick requires the pipeline to be embedded in a "do" loop because Stop-Pipeline basically just calls "Continue" when the condition is met, making the do loop abort what it was doing (executing the pipeline).

This sounds awkward but works beautifully. Here is a slight adaption. It will run the pipeline for a maximum of 10 seconds:

$start = Get-Date
$MaxSeconds = 10

do {
    Get-ChildItem c:\Windows -Recurse -ErrorAction SilentlyContinue | Stop-Pipeline { ((Get-Date) - $start).TotalSeconds -gt $MaxSeconds } 
} while ($false)

Simply place a variable before the "do" statement if you want to save the pipeline results rather than outputting them.

$result = do {
    Get-Chil...

Twitter This Tip! ReTweet this Tip!