PowerShell: How to Get Values from Header of CSV


Often you may want use PowerShell to get the values from the header row of a CSV file.

You can use the following syntax to do so:

$my_data = Import-Csv nba_data.csv
$header_values = $my_data[0].psobject.properties.name

This particular example extracts only the values from the header row of the CSV file named nba_data.csv and stores them in an array named $header_values.

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

Example: How to Get Values from Header of CSV File in PowerShell

Suppose we have a CSV file in our current directory named nba_data.csv.

We can use the Import-Csv cmdlet to view the contents of this file:

The file contains four columns that show the team , points, assists and rebounds for various basketball players.

Suppose that we would like to extract only the values from the header of this CSV file.

We can use the following syntax to do so:

$my_data = Import-Csv nba_data.csv
$header_values = $my_data[0].psobject.properties.name

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

PowerShell get values from header of CSV

Notice that this returns an array that contains the values from the header row of the CSV file.

Note that we could also bracket notation to extract a specific value from the header row.

For example, we could use the following syntax to extract the value in index position 1 of the header row:

$header_values[1]

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

Notice that this returns the value points, which represents the value in index position 1 of the header row of the CSV file.

Related Tutorials

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

PowerShell: How to Use Import-Csv and Extract Specific Columns
PowerShell: Use Import-Csv Where Row Contains String
PowerShell: How to Use Import-Csv with No Headers
PowerShell: How to Use Import-Csv and Foreach

Leave a Reply