ExpandProperty rocks – sometimes

by May 11, 2010

Select-Object will select the object properties that you want to see. So it removes all properties you did not specify, but it always returns an object:

Get-Process | Select-Object Name

Often, you are not interested in an object but prefer the content of an object property. When you specify -ExpandProperty, Select-Object will actually take an object and replace the entire object with the content of one of its properties:

Get-Process | Select-Object -ExpandProperty Name

This is extremely useful and roughly the equivalent of this:

Get-Process | Foreach-Object { $_.Name }

However, you should note that -ExpandProperty has a bug in v2 that can occur with certain object types. So if the result returned by -ExpandProperty raises strange exceptions when you process it, you should use the Foreach-Object approach, which always works right.

Twitter This Tip! ReTweet this Tip!