34

我想在powershell中处理一个csv文件,但我不知道处理它时CSV文件中的列标题是什么。

例如:

$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)
    }

}

如何遍历 csv 文件中的行,获取列的名称和值?还是我应该这样做的另一种方式(比如不使用 Import-csv)?

4

3 回答 3

51
Import-Csv $path | Foreach-Object { 

    foreach ($property in $_.PSObject.Properties)
    {
        doSomething $property.Name, $property.Value
    } 

}
于 2012-08-09T14:13:56.837 回答
16

遍历 CSV 文件每一行的每一列的另一种方式是

$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 
    }
} 

所以您可以选择:您可以使用$column.Name获取列名或$i获取列号

于 2015-12-07T10:55:06.063 回答
1
$header3 = @("Field_1","Field_2","Field_3","Field_4","Field_5")     

Import-Csv $fileName -Header $header3 -Delimiter "`t" | select -skip 3 | Foreach-Object {

    $record = $indexName 
    foreach ($property in $_.PSObject.Properties){

        #doSomething $property.Name, $property.Value

            if($property.Name -like '*TextWrittenAsNumber*'){

                $record = $record + "," + '"' + $property.Value + '"' 
            }
            else{
                $record = $record + "," + $property.Value 
            }                           
    }               

        $array.add($record) | out-null  
        #write-host $record                         
}
于 2017-09-22T15:46:05.410 回答