1
votes

I have a script that needs to run both on Powershell v2.0 and v3.0 It imports a csv file and reads a particular value from the first row only. The csv file can have a single row of values or multiple.

$file_data = Import-csv -Path $file_name

$col5 = "ColumnName"

...

then use $file_data[0].$col5 in some statement

Here's the difference in Import-csv's behavior between Powershell v2.0 and v3.0

  1. On Powershell v2.0, Import-csv returns a non array PSObject object when there is a single row in csv file. So, the above line will throw an error "CannotIndex" $file_data. But when you have multiple rows in csv, Powershell v2.0 will work fine.

  2. On Powershell v3.0, Import-csv always returns an array, so indexing is not a problem.

But if I remove the index and use just $file_data.$col5, Powershell v2.0 will not show any data when the csv has multiple rows.

I am missing out on some thing here. There should be an elagant way to deal with it.

1

1 Answers

2
votes

Why not enclose the import-csv cmdlet with @() notation that return always an array, also in case of a single value and valid in V2 and V3?

$file_data = @(Import-csv -Path $file_name)