How To Get The Value Of Header In CSV How To Get The Value Of Header In CSV powershell powershell

How To Get The Value Of Header In CSV


If you have an object in $obj, you could list all the property headers like this:

$obj | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name'

This is an array, so you can reference them individually like this:

($obj | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name')[0]

This would just give you the name of the first property for instance.


Assuming that you have already read in the CSV using Import-CSV you can examine the property of the resulting object. Similar to this answer but maintains column order in the resulting array

Examining the first row / element

$data = import-csv $path$data[0].psobject.properties.name

So the second line will return a string array of the properties.


To get the column name from the csv, first, put the names of the column headers into an array (this will also allow you to loop through each column, if needed) ...

$inFilePath = "C:\path\to\file.csv"$csvColumnNames = (Get-Content $inFilePath | Select-Object -First 1).Split(",")

... , secondly, index into the array by column position (index starts at 0). Given your original example it would be;

$myCountryColumnName = $csvColumnNames[2]