PowerShell: Use Select-Object to Only Get Property Value


Often you may want to use the Select-Object cmdlet in PowerShell to only select a property’s value without the property name.

You can use the -ExpandProperty statement to do so:

Get-ChildItem $my_folder | Select-Object -ExpandProperty Name

This particular example does the following:

  • First, use the Get-ChildItem cmdlet to get all files and folders for the directory specified by $my_folder.
  • Then, use the Select-Object cmdlet with -ExpandProperty to only get the values from the Name column of the output.

You can also just use -Expand to make the syntax shorter:

Get-ChildItem $my_folder | Select-Object -Expand Name

The following example shows how to use this syntax in practice.

Example: Use Select-Object to Only Get Property Value in PowerShell

Suppose we have a directory located at the following path:

  • c:\users\bobbi\data1

We can use the Get-ChildItem cmdlet to view all files and folders in this directory:

$my_folder = 'c:\users\bobbi\data1'
Get-ChildItem $my_folder

The following screenshot shows how to use this syntax in practice:

Notice that this returns an object with four properties: Mode, LastWriteTime, Length and Name.

Suppose that we would like to use the Select-Object cmdlet to only select the Name column:

Get-ChildItem $my_folder | Select-Object Name

The following screenshot shows how to use this syntax in practice:

Notice that this returns both the name of the property along with the values of the property.

If we would instead like to return the property’s values only, then we can use the -ExpandProperty statement:

Get-ChildItem $my_folder | Select-Object -ExpandProperty Name

The following screenshot shows how to use this syntax in practice:

PowerShell Select-Object to get value only

Notice that this returns only the values from the Name column.

Also note that we could shorten the code slightly by just using the -Expand statement:

Get-ChildItem $my_folder | Select-Object -Expand Name

The following screenshot shows how to use this syntax in practice:

Once again, this returns only the values from the Name column.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Use Sort-Object with Multiple Properties
PowerShell: How to Use Where-Object in List

Leave a Reply