How Does Member Enumeration Work in PowerShell 3?

瘦欲@ 提交于 2019-12-11 03:48:46

问题


In PoweShell 2 we did:

Get-ChildItem | ForEach-Object {$_.LastWriteTime} | Sort-Object  

In Powershell 3 we do:

(Get-ChildItem).LastWriteTime | Sort-Object

But how does it work, i read this blog post on MSDN and they say that its faster because the foreach loop isnt running? So how does it enumerate the properties then ?


回答1:


PowerShell is doing the hard work for us and it loops over the collection internally. I like to call this "implicit foreach". Assuming the member you specified is present on each object, if the member you specified is a property, you get back its value. If it's a method, it invokes the method on the each object.

In v2, to get all process names you had to take care of looping yourself:

Get-Process | Foreach-Object {$_.Name}

In v3, the equivalent would be:

(Get-Process).Name

Same applies to methods. To kill all processes with name starting with note*:

(Get-Process note*).Kill()



回答2:


The blog says foreach-object cmdlet is not running. Now it is taken care of by the language engine and not a cmdlet, making it faster. How it EXACTLY works is internal implementation detail and I think that is not what you really want to know.



来源:https://stackoverflow.com/questions/12131416/how-does-member-enumeration-work-in-powershell-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!