I was tinkering around with a script the other day and came across a requirement I have in nearly every script. The requirement was to iterate through a collection of objects, do something to each of the object’s properties in the fastest, most efficient way possible and eventually get a collection of strings as output. I started out just throwing in my usual method of doing this via Select-Object’s calculated properties and I got to thinking if there’s a better way. Usually, I have less than a few thousand objects to iterate through but what if I had millions? Using a calculated field surely can’t be the best way, can it? I set out to find the truth.

I decided to post up a Powershell.org forum thread entitled Is there a better way to expand a calculated field? that raised the question to others and I got a few interesting replies and thought I would expound on that thread a little bit here.

I decided to time each of the suggestions I received in terms of code length and speed as well as a couple other methods I knew about. Below are the results:

Here’s the collection I created to do the testing on.

Here are the results of my testing:

As you can see the bottom method of using Powershell v3’s method of encapsulating the collection and property name in parens and then using that to pass to the next operation was by far the fastest and shortest code. Be aware that this is only present in Powershell v3 but I’m assuming this wont’ be much of a problem for most people.

What’s this mean? Other than me burning a couple hours tinkering around on a Sunday, you now know if you’ve got a huge collection of objects to go through try to use the format: