找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 13786|回复: 0

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

[复制链接]
发表于 2014-2-28 09:45:42 | 显示全部楼层 |阅读模式
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
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-17 01:06 , Processed in 0.016452 second(s), 8 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表