Reputation: 15
I have this CSV file. Looks like this:
ID,Name,Surname,Energy, Sugar 1,Kim,Jansen,4343,45 2,Tim,Brown,5332,42 3,Paul,Redford,2345,36
I have a Read-Host
statement in my script which asks for the ID. Once I have this - let's say it is 2 - I now want to import this CSV file and read the row where ID=2 and save the Name, Surname, Energy and Sugar in variables.
I have tried with ForEach-Object
and so on, but it prints all the ID columns and saves only the last row.
How do I get the row values only if the if
condition is true?
Upvotes: 0
Views: 184
Reputation: 200503
Simply use a Where-Object
filter:
$id = Read-Host ...
$row = Import-Csv 'input.csv' | Where-Object { $_.Id -eq $id }
You can store the fields of the CSV in individual variables:
$name = $row.Name
$surname = $row.Surname
$energy = $row.Energy
$sugar = $row.Sugar
but that's usually neither required nor recommended. Just use the properties of your object variable ($row
in this example).
Upvotes: 1