PowerShell 3 中的成员枚举如何工作? [英] How Does Member Enumeration Work in PowerShell 3?

查看:37
本文介绍了PowerShell 3 中的成员枚举如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PoweShell 2 中,我们做到了:

In PoweShell 2 we did:

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

在 Powershell 3 中,我们这样做:

In Powershell 3 we do:

(Get-ChildItem).LastWriteTime | Sort-Object

但是它是如何工作的,我阅读了这篇博客在 MSDN 上发帖,他们说它更快,因为 foreach 循环没有运行?那么它是如何枚举属性的呢?

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 ?

推荐答案

PowerShell 为我们做了繁重的工作,它在内部循环遍历集合.我喜欢称之为隐式 foreach".假设您指定的成员存在于每个对象上,如果您指定的成员是一个属性,则您将取回其值.如果是方法,则调用每个对象上的方法.

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.

在 v2 中,要获取所有进程名称,您必须自己处理循环:

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

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

在 v3 中,相当于:

In v3, the equivalent would be:

(Get-Process).Name

同样适用于方法.要杀死名称以 note* 开头的所有进程:

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

(Get-Process note*).Kill()

这篇关于PowerShell 3 中的成员枚举如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆