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 exe files in your folder:
PS C:\Test> Get-ChildItem -Path C:\Test -Filter *.exe -Recurse -ErrorAction SilentlyContinue | Select-Object -First 4
Directory: C:\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2/3/2009 3:09 PM 150016 7z.exe
-a--- 7/6/2007 7:51 PM 36352 Base64.exe
-a--- 9/2/2008 1:42 PM 279040 curl.exe
-a--- 12/2/2013 10:35 PM 223246 gawk.exe
|
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.
http://powershell.com/cs/blogs/tips/archive/2014/02/27/save-time-with-select-object-first.aspx |