Select –ExpandProperty <PropertyName>

Most of us are familiar with the traditional use of Select –ExpandProperty <propertyname>.  This takes a the value of an incoming object, enumerates its values and outputs each of those values as a single record on the output stream after adding any properties specified by the –PROPERTIES <propertyname[]> parameter.  An example will help:

PS> gps |Select -ExpandProperty Modules -ea SilentlyContinue |Group ModuleName |Sort Count |Select -Last 4

Count Name                      Group
—– —-                      —–
   58 kernel32.dll              {System.Diagnostics.ProcessModule (kernel32….
   58 msvcrt.dll                {System.Diagnostics.ProcessModule (msvcrt.dl…
   58 KERNELBASE.dll            {System.Diagnostics.ProcessModule (KERNELBAS…
   72 ntdll.dll                 {System.Diagnostics.ProcessModule (ntdll.dll…

 

 

A while ago, Lee Holmes turned me on to another use of –ExpandProperty and I’ve been meaning to blog it ever since.  Have you ever wanted to get just the value for a property from every object?  You’d think you could do this and it would work:

PS> gps *ss |select name

Name
—-
csrss
csrss
lsass
smss

 

Sadly, this is not what you want. This gives you a set of objects each of which has exactly one property:  NAME.  What you wanted was a stream of VALUES.  What I’ve always ended up doing was this:

 

PS> gps *ss | foreach {$_.Name}
csrss
csrss
lsass
smss

 

 

This works, it is not too hard but it always sorta pissed me off that I had to do it this way.  Sadly, addressing this never made it above the cut like for V2.  Again – to ship is the choose.  I was complaining about this one day and Lee pointed out that if you specify a scalar property (a property that is NOT a collection) for –ExpandProperty – it gives you exactly what you want.

PS> gps *ss |select -ExpandProperty name
csrss
csrss
lsass
smss

 

SWEET!

Enjoy!

Jeffrey Snover [MSFT]
Distinguished Engineer
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx