It is called Member Enumeration and not Implicit Foreach – Part 2

Last week I wrote a post about Member Enumeration (a new feature in PowerShell v3), specifically about that it’s called that and not Implicit Foreach.
Although my previous post does go into a little bit of detail, I’ve chosen the wrong examples to show the capabilities of Member Enumeration. That’s why I’ve written this post: Better examples and a clear clarification of the feature itself.

The problem and solution
Most new features will solve a problem.¬†Member Enumeration solves the problem scripters have with of returned objects, specifically the fact that you don’t know what objects are returned. Is it one or are they many? Is it a string or an array? By using Member Enumeration, PowerShell will handle the differences for you under the hood. So no worries, just let PowerShell do all the hard work for you.
Let’s explain that.

In PowerShell v2 you would have to do something like:

Or for the more experienced scripters, you could also do:

Now with Member Enumeration you can simply do:

You’ll notice that the output is the same in all three cases. So what’s the diff?
There are four major differences:

  1. The Select-Object or Foreach-Object cmdlet is not used with Member Enumeration. This makes it faster but it still shows you the same result.
  2. It doesn’t matter if you’ll get one or many objects returned, you can handle it the same way.
  3. The syntax is much easier to learn and use.
  4. It’s less characters so less typing and less code.

But you can also use methods the same way as I’ve called the property name as shown above:

This is nothing new compared to my previous post.

What else can you do with it?

And now we get to the cool stuff.
What if you were to get all process names from your device and show the names in uppercase? In PowerShell v2 you’ll need something like:

Now with Member Enumeration:

As you can see, it’s shorter, easier to type, easier to learn and most of all, the Foreach-Object cmdlet is not used.
But what did I do here?
I’m using the Member Enumeration syntax to enumerate all processes and select the only the name for those processes.
Next, I’m simply attaching the ToUpper method to it and voil√° the names are converted to uppercase.
Note that another new feature called ‘Automatic Foreach’ is used here. I’ll write another post about this in a few hours.

Tip: If you want to know which properties and methods are available to you at each point simply pipe the objects to the Get-Member cmdlet:

Although I’m focussing a lot on the syntax you can use for Member Enumeration when used in oneliners, the strength of Member Enumeration lies in the fact that it does the object handeling for you.
No more annoyances when you don’t know if you’ll be returned one or multiple objects.
And for me as a practical guy it means less, faster and easier code.

Leave a Reply

Your email address will not be published. Required fields are marked *