Home > Back-end >  Powershell: Create multiple PSCustomObjects from 3 arrays with different length
Powershell: Create multiple PSCustomObjects from 3 arrays with different length

Time:12-12

It is a beginner question but after hours of hours trying, i still do not know, what is better than create 3 different forloops, or one with if-decisions:

Example Code:

$a = 1,2,3
$b = 5,6,7,8,9
$c = 4, 10

$test = [PSCustomObject]@{
    A = $a
    B = $b
    C = $c
}

$test

I get output:

A         B               C      
-         -               -      
{1, 2, 3} {5, 6, 7, 8...} {4, 10}

I try with this easy example, what is best to export a csv-file with a header for each column(like above) but with values not in one line as here.So i get a headered table of all 1000 values in the real problem. An extra file for each column seems also not the best solution..

I'm searching for a version to get output like(but for all data):

A,B,C
1,5,4
2,6,10
3,7,
,8,
...

I can get this when i iterate through the input and create a PSCustomObject for each line, but when i think of the different length i think of 3 loops. Of one loop with some extra-code to avoid Index-Errors. Something always tells me, that this is an easy task, but i can't find an elegant solution.

I appreciate every idea!

Thank you

CodePudding user response:

Here is one way of doing this using a while loop and Measure-Object to get the maximum count of elements on the 3 arrays:

$a = 1,2,3
$b = 5,6,7,8,9
$c = 4,10

$max = $a.Count, $b.Count, $c.Count | Measure-Object -Maximum
$i = 0

$result = while($max.Maximum--)
{
    [pscustomobject]@{
        A = $a[$i]
        B = $b[$i]
        C = $c[$i]
    }
    $i  
}

Now looking at your expected output, seems like you want to export the data to a CSV, in that case you would use Export-Csv, if you just want to have the data converted but without exporting it you can use ConvertTo-Csv:

PS /> $result | ConvertTo-Csv -NoTypeInformation

"A","B","C"
"1","5","4"
"2","6","10"
"3","7",
,"8",
,"9",
  • Related