PowerShell 3.0–Now with Property Unrolling!

There are many new improvements to the language and parser in v3 (some of which I hope to cover over the next few posts) but one of my favourites is what Microsoft are calling singleton/array enumeration (or something equally obtuse.) I am hereby christening it “Property Unrolling” as it works similarly to how PowerShell does automatic collection unrolling when piping an enumerable (list, collection, array.)

This powershell 3.0 technique is where you can take a variable that contains an array (or collection, list or anything else that is enumerable) like $myarray and if you want to access a property on each element in that array, you no longer need to use foreach-object with $_.propertyName to access it. Instead, you can simply type $myarray.propertyName and powershell will return that property from each element in the array, but only if the array itself does not have that property. For example if you had an array of strings, asking for $arr.length would return the length of the array, and not the length of each string. The best way to show this is with some examples:

Array of files

# the older way (still works)
dir | foreach-object { $_.lastwritetime } | sort

# now, here's the shortcut way for v3
(dir).lastwritetime | sort

XML

Here's an example on how working with XML just got ten times easier. Here's some XML:

    
                     
             42
        
                     
             43
        
                     
             44
        
    

Here's a script that dumps the prop value in each element:

# the older way
$xml = [xml]" ... "
$xml.root.element | foreach-object { $_.prop }

# the v3 way ;)
$xml.root.element.prop

This is such a time saver. Thank you Microsoft!

About the author

Irish, PowerShell MVP, .NET/ASP.NET/SharePoint Developer, Budding Architect. Developer. Montrealer. Opinionated. Montreal, Quebec.

Month List

Page List