Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I loop through a line from a csv file in powershell

Tags:

powershell

csv

I want to process a csv file in powershell, but I don't know what the column headings in the CSV file will be when it is processed.

For example:

$path = "d:\scratch\export.csv" $csv = Import-csv -path $path  foreach($line in $csv) {      foreach ($head in $line | get-member | where-object {$_.MemberType -eq "NoteProperty"} | select Definition)     {         #pseudocode...         doSomething($head.columnName, $head.value)     }  } 

How do I loop through the line in the csv file, getting the name of the column and the value? Or is there another way I should be doing this (like not using Import-csv)?

like image 400
simon Avatar asked Aug 09 '12 14:08

simon


2 Answers

Import-Csv $path | Foreach-Object {       foreach ($property in $_.PSObject.Properties)     {         doSomething $property.Name, $property.Value     }   } 
like image 148
Shay Levy Avatar answered Oct 17 '22 03:10

Shay Levy


A slightly other way of iterating through each column of each line of a CSV-file would be

$path = "d:\scratch\export.csv" $csv = Import-Csv -path $path  foreach($line in $csv) {      $properties = $line | Get-Member -MemberType Properties     for($i=0; $i -lt $properties.Count;$i++)     {         $column = $properties[$i]         $columnvalue = $line | Select -ExpandProperty $column.Name          # doSomething $column.Name $columnvalue          # doSomething $i $columnvalue      } }  

so you have the choice: you can use either $column.Name to get the name of the column, or $i to get the number of the column

like image 28
user4531 Avatar answered Oct 17 '22 03:10

user4531