Aborting the PowerShell Pipeline (Part 1: Select-Object)

by Dec 18, 2019

Sometimes it can save a lot of time to manually abort a PowerShell pipeline. For example, if you don’t know exactly where a file is located and start a recursive search, the search could be aborted once you found your file. There is no reason why it should continue to search the rest of the directories.

Here is a scenario illustrating the problem: let’s assume you are searching for a file called “ngen.log” somewhere in your Windows folder:

$fileToSearch = 'ngen.log'

Get-ChildItem -Path c:\Windows -Recurse -ErrorAction SilentlyContinue -Filter $fileToSearch 

PowerShell will find the file but continues to search the rest of the directory tree which takes a long time.

If you know how many results you are after, you can use Select-Object to abort the pipeline once the results are in:

$fileToSearch = 'ngen.log'
Get-ChildItem -Path c:\Windows -Recurse -ErrorAction SilentlyContinue -Filter $fileToSearch |
Select-Object -First 1

In this example, PowerShell immediately returns when the file is found. As a best practice, if you know beforehand how many results you need from a command, append a Select-Object to the pipeline, and use the -First parameter to tell PowerShell the required number of results.


Twitter This Tip! ReTweet this Tip!