How to read the first column of a CSV file with powershell

Viewed 1532

I'm trying to read a CSV file with powershell.

I currently do the following:

#Reading CSV
$stats = Import-Csv -Path $counterFile -Delimiter $separator

And now I need to extract the column values in differents objects.

I've seen that I should be able to access it like this:

$stats.ColumnHeader

The issue is that this column contains dates, and a genius decided that the header of this column would be the timezone of the computer in a weird format.

So how can I read the first column without "knowing" the header text and without modifying the other columns headers?

Is there a way to access this column through indexes?

1 Answers

Each PSCustomObject has a few hidden properties:

$Stats |Get-Member -Force

Name        MemberType   Definition
----        ----------   ----------
pstypenames CodeProperty System.Collections.ObjectModel.Collection`1[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]] pstypenames{get=PSTypeNames;}
psadapted   MemberSet    psadapted {ToString, GetType, Equals, GetHashCode}
psbase      MemberSet    psbase {ToString, GetType, Equals, GetHashCode}
psextended  MemberSet    psextended {Id, Name, Country, EMail, Age, ReportsTo}
psobject    MemberSet    psobject {BaseObject, Members, Properties, Methods, ImmediateBaseObject, TypeNames, get_BaseObject, get_Members, get_Properties, get_Methods, get_ImmediateBaseObject, get_TypeNames, ToString, Copy, CompareTo, Equals, GetHash…
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
...         NoteProperty ...

Where the PSObject property contains a Properties property containing child properties along with the Name and the Value of each $Stats property.
In other words, to find out the name of the first $Stats[0] property (aka first column), you can do:

$Stats[0].PSObject.Properties.Name[0]
ColumnHeader

And to retrieve all the values of that column:

$ColumnName = $Stats[0].PSObject.Properties.Name[0]
$Stats.$ColumnName

Or:

$Stats.($Stats[0].PSObject.Properties.Name[0])
Related