Aborting the Pipeline

by May 8, 2015

If you know beforehand how many results you expect from a pipeline, you can use Select-Object to stop the upstream cmdlets. This can save a lot of time.

This example tries to find the first instance of explorer.exe inside the Windows folder. Because of the Select-Object statement, the pipeline finishes the moment the first instance is found. Without it, Get-ChildItem would continue to recursively scan the Windows folder although you already have what you wanted.

#requires -Version 3

Get-ChildItem -Path c:\Windows -Recurse -Filter explorer.exe -ErrorAction SilentlyContinue |
Select-Object -First 1

Note that the ability to stop upstream cmdlets was added to Select-Object only in PowerShell 3.0. In earlier versions, you would still get only the first x elements, but the upstream cmdlets would continue to run and not get notified that all required results already came in.

Twitter This Tip! ReTweet this Tip!