Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

How Does Member Enumeration Work in PowerShell 3?

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...