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.
## Create the source collection of objects with at least 1 property $TestCollection = Get-WmiObject -Class CIM_Datafile | Select -first 50000
The 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 won't 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:
($Collection.PropertyName) | Do-SomethingHere
Join the Jar Tippers on Patreon
It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!Become a Patron!