Search code examples
csvpowershellforeachpowershell-3.0export-to-csv

Reading values from CSV and output them in the format Column1:Row1, Column2:Row1


I am trying to write simple PowerShell code to read two columns values from CSV and print in manner like

1

201

2

202
.
.

CSV File:

PRODID  DEVID   Name

1       201    Application

2       202    Product

3       203    Component

4       204    Author

5       205    Version

Powershell Code:

$DEVID = Import-Csv C:\test\install.csv | % {$_.DEVID}
$PRODID = Import-Csv C:\test\install.csv | % {$_.PRODID}

ForEach ($DEVI in $DEVID)
{
    Write-Host $DEVI

    ForEach ($PRODI in $PRODID)
    {[enter image description here][1]
      Write-Host $PRODI     
    }
} 

But I am not getting expected output, though I have tried break, continue syntax. Can anyone help me in this case please?


Solution

  • You only need to import your csv once. Then just iterate over it and output your desired records:

    Import-Csv 'C:\test\install.csv' | Foreach { 
       $_.PRODID; $_.DEVID; 
    }
    

    Output:

    1
    201
    2
    202
    3
    203
    4
    204
    5
    205
    

    If this doesn't work, you have to show us your csv file.