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)?
Import-Csv $path | Foreach-Object { foreach ($property in $_.PSObject.Properties) { doSomething $property.Name, $property.Value } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With