ForeEach loop with CSV

Hi, i try get information out of csv file and then save it to variables so I can use it later in the script. I would want use only first row of the csv file (really 2nd row because headers are 1st)

Example csv file

…A B C

1 Car Model Year

2 Ford Fiesta 2015

3 Audi A6 2018

In this example, i would like to save Ford, Fiesta and 2015 to variables (row 1)($Card, $Model, $Year) and after it delete the row. The 2nd row should not be deleted, because it is used later on with the same script.

Here are my current script.

$cars = import-csv "C:\path\"
ForEach ($data in $cars){
$Car = $cars.car
$model = $cars.model
$year = $cars.year
}
Issue:

$Cars shows all data from the last row, $Data shows all data from all rows but rest variables don’t show anything, where’s issue? I should also probably use command Select-Object -First 1 to get data from only 1st row and Select-Object -Skip 1 to delete the row, but where to put those.

 

 

Read CSV row 1 columns and save them to variables.
You marked one of my replies in the Microsoft forum as answer - now you’re asking here again. What’s the actual task you want to solve? What do you like to do actually?
You might have some misunderstandings about how Powershell handles data. So you wouldn’t need separate variables for singly columns from a CSV file par example. You can save a complete row in one array variable (par example: $row) and access the single “fields” by using their column name like this: $row.ColumnName .

Edit: By the way: In your code you did a mistake. Inside your loop you should use $data.car, $data.model and $data.year instead of $cars.car, $cars.model and $cars.year. :wink:

Not sure if this is what you are looking for, but hope it helps.

[pre]
$cars = @’
Make,Model,Year
Saturn,LW200,2003
VM,Jetta,2010
'@ | ConvertFrom-Csv

$data = $cars | Select-object -first 1 -property Make, Model
$data.Make
$data.Model
[/pre]

are you sure on

$Cars shows all data from the last row, $Data shows all data from all

it should be other way around. And when you say to save to variables, are you expecting the variable to be array of make, model and year ?

IMO the variable $Cars is enough for any uses case in a script. Can you let us know what you will be doing by having those in separate variables ?

Hi, I got this already solved.

Cool. So please enlighten us and share your solution. Others might consider this helpful.