2

When dealing with csv files using the cmdlet Import-Csv in PowerShell, is there an easy / elegant way to query a column by its position instead of the header name?

Example with this data:

row1, abc
row2, def
row3, xyz

The below command works fine if the file has "header_column2" as the header of the 2nd column:

import-csv data.csv | where {$_.header_column2 -eq "xyz"}

I am looking for something like this (which obviously doesn't work!):

import-csv data.csv | where {$_.[2] -eq "xyz"}

I know that if I don't have headers in the file I could use the -Header parameter to specify those, but I am looking for something quick and handy to write on the fly for various files, where headers are not relevant.

Many thanks!

bdista
  • 23
  • 1
  • 3

1 Answers1

2

Since @PetSerAl doesn't understand the difference between comments and answers here at StackOverflow, I'll provide a similar answer.

You can list the properties in the object using .PSObject.Properties. This returns an IEnumerable that doesn't know about indexes, but if you convert it to an array, it will.

@($_.PSObject.Properties)[2].Value
Frode F.
  • 52,376
  • 9
  • 98
  • 114