Save Time With Select-Object -First!

by Feb 27, 2014

Select-Object has a parameter called -First that accepts a number. It will then return only the first x elements. Sounds simple, and it is.

This gets you the first 4 PowerShell scripts in your Windows folder:

Beginning in PowerShell 3.0, -First not only selects the specified number of results. It also informs the upstream cmdlets in the pipeline that the job is done, effectively stopping the pipeline.

So if you have a command where you know that after a certain number of results, you are done, then you should always add Select-Object -First x – this can speed up your code dramatically in certain cases.

Let's assume you are looking for a file called "test.txt" somewhere in your home folder, and let's assume there is only one such file. You just do not know where exactly it is located, so you use Get-ChildItem and -Recurse to recursively search all folders:

Get-ChildItem -Path $home -Filter test.txt -Recurse -ErrorAction SilentlyContinue

When you run this, Get-ChildItem will eventually find your file – and then continue to search your folder tree. Maybe for minutes. It cannot know whether or not there may be additional files.

You know, though, so if you know the number of expected results beforehand, try this:

Get-ChildItem -Path $home -Filter test.txt -Recurse -ErrorAction SilentlyContinue |
  Select-Object -First 1 

This time, Get-ChildItem will stop immediately once the file is found.

Twitter This Tip! ReTweet this Tip!