[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[转载代码] [PowerShell每日技巧]使用Select-Object -First节省时间提高效率(20140227)

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:
  1. 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:
  1. Get-ChildItem -Path $home -Filter test.txt -Recurse -ErrorAction SilentlyContinue |
  2.   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

返回列表