Home > OS >  Different length arrays to one CSV
Different length arrays to one CSV

Time:09-08

If you have multiple arrays of different length, how can you export these to a single csv in powershell?

Array1 = 1,2,3 
Array2 = Bob,smithy,Alex,Jeremy 
Array3 = yes,no

Output CSV

Number  Name  Valid 
———————————————————  
1      Bob    Yes  
2      Smithy no  
3      Alex
       Jeremy

Basically each array would be in its own header column.

Tried lines like

Array1 | Select-Object Number | export-csv -Path C:\Path

This works for singular arrays to singular csv files

But if I try

Array1, Array2, Array3 | Select-Object Number, Name, Valid | export-csv -Path C:\Path

I just get the header names and no values in the columns

CodePudding user response:

One way to do it is with a for loop.

$Array1 = 1,2,3
$Array2 = 'Bob', 'smithy,Alex', 'Jeremy'
$Array3 = 'yes', 'no'

$export = for($i = 0; $i -lt [Linq.Enumerable]::Max([int[]] ($Array1.Count, $Array2.Count, $Array3.Count)); $i  ) {
    [pscustomobject]@{
        Number = $Array1[$i]
        Name   = $Array2[$i]
        Valid  = $Array3[$i]
    }
}
$export | Export-Csv path\to\csv.csv -NoTypeInformation

CodePudding user response:

You need to restructure the data to pivot it into one array (presented here in pseudo-json):

[ 
  {"1", "Bob", "Yes"}, 
  {"2", "Smithy", "no"}, 
  {"3", "Alex", ""}, 
  {"", "Jeremy", ""} 
]

Note how the missing fields still appear with empty placeholders.

Once you've pivoted your data this way, writing it to a CSV file is trivial, as are many other tasks (this is the better way to structure things in the first place).

  • Related