In the category of ‘new things in PowerShell v3’ I’ll cover a something called Member Enumeration in this post.
Do you remember when the first bits of PowerShell v3 came out? You started to play with it and blog about it… and before you knew it the community found a very cool new feature they called Implicit Foreach. As did I by the way 😉
So when I was writing my chapter for the PowerShell Deep Dives book I wanted to cover a little bit of this feature in my chapter. I couldn’t find any official documentation about this feature… not on TechNet or even in the help. So I did what I always do when I encounter something like this: I asked the vendor. I actually got a very quick response which was exactly what I needed.
So what happened here? I was looking for a feature with a wrong name. The official name of this feature is not Implicit Foreach but Member Enumeration!
That would explain why I wasn’t able to find anything about it 😉
What is Member Enumeration?
Let’s start with the basics: What is it? I’ve got a simple explanation with an analogy to some math for this… Why? Well, you actually already know what Member Enumeration is and you didn’t even realized it 😉
Back when you were still in high school your Mathematics teacher told you that in math, everything put between () is calculated first. This is the syntax of Member Enumeration when used in oneliners. Easy, right?
So what is the main benefits that Member Enumeration brings us?
In my opinion there is one major benefit: When using Member Enumeration you won’t have to care if it’s returing a single object or a whole bunch of objects. Under the hood, PowerShell will enumerate and handle all the differences for you.
What can you do with Member Enumeration?
Anything attached to the objects that you enumerate can be used… so properties, methods, etc.
Alright, alright… let’s take a look at some examples.
First up are properties. When you would want to get the names of all processes, before PowerShell v3, you would have to use pipelined expressions and the Select-Object cmdlet:
Now, with Member Enumeration, you can simply do:
Second, how about using Member Enumeration for applying methods? Simply do the same as with properties:
But wait, it will get even crazier easy…
How would you get a count of the running processes on your system? Not the name of the property or something like that… only the actual number.
You would probably use something like:
Now let’s do that with Member Enumeration:
Now isn’t that a lot easier and shorter?
How do you find the properties and methods (such as ‘count’) that are available when you use Member Enumeration? The same way as you would do it with any object, by using the Get-Member cmdlet:
Note: Since this post made me receive quite some questions and remarks in my mailbox I’ll write another post this week explaining Member Enumeration with better examples and a bit more detailed explenation.