Read Column data from CSV

前端 未结 1 764
北荒
北荒 2021-01-26 12:58

I have a CSV file

Name,Age,Data
Test,22,Yes
Test2,23,No
Test3,43,Yes

How can I process this file using PowerShell, so that I can replicate thi

相关标签:
1条回答
  • 2021-01-26 13:27

    The PowerShell equivalent of your pseudo code would be something like this:

    $csv = Import-Csv 'C:\path\to\your.csv'
    
    $headers = $csv | Get-Member -MemberType NoteProperty | select -Expand Name
    
    foreach ($header in $headers) {
      foreach ($data in $csv.$header) {
        # do stuff with $data
      }
    }
    

    For better answers take a step back and describe the actual problem you're trying to solve instead of what you perceive as the solution.

    Demonstration:

    PS C:\> $csvfile = 'C:\temp\test.csv'
    PS C:\> Get-Content $csvfile
    Name,Age,Data
    Test,22,Yes
    Test2,23,No
    Test3,43,Yes
    PS C:\> $csv = Import-Csv $csvfile
    PS C:\> $csv | Format-Table -AutoSize
    
    Name  Age Data
    ----  --- ----
    Test  22  Yes
    Test2 23  No
    Test3 43  Yes
    
    PS C:\> $headers = $csv | Get-Member -MemberType NoteProperty | select -Expand Name
    PS C:\> $headers
    Age
    Data
    Name
    PS C:\> foreach ($header in $headers) {
    >>   foreach ($data in $csv.$header) {
    >>     Write-Host $data
    >>   }
    >> }
    >>
    22
    23
    43
    Yes
    No
    Yes
    Test
    Test2
    Test3
    0 讨论(0)
提交回复
热议问题