Select the values of one property on all objects of an array in PowerShell

Sylvain Reverdy picture Sylvain Reverdy · Mar 3, 2011 · Viewed 254.4k times · Source

Let's say we have an array of objects $objects. Let's say these objects have a "Name" property.

This is what I want to do

 $results = @()
 $objects | %{ $results += $_.Name }

This works, but can it be done in a better way?

If I do something like:

 $results = objects | select Name

$results is an array of objects having a Name property. I want $results to contain an array of Names.

Is there a better way?

Answer

Scott Saad picture Scott Saad · Mar 3, 2011

I think you might be able to use the ExpandProperty parameter of Select-Object.

For example, to get the list of the current directory and just have the Name property displayed, one would do the following:

ls | select -Property Name

This is still returning DirectoryInfo or FileInfo objects. You can always inspect the type coming through the pipeline by piping to Get-Member (alias gm).

ls | select -Property Name | gm

So, to expand the object to be that of the type of property you're looking at, you can do the following:

ls | select -ExpandProperty Name

In your case, you can just do the following to have a variable be an array of strings, where the strings are the Name property:

$objects = ls | select -ExpandProperty Name