One way to do it is with a for loop.
$Array1 = 1, 2, 3
$Array2 = 'Joe Bloggs', 'John Doe', 'Jane Doe'
$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
Another example using a function, the logic is more or less the same except that there is more overhead involved, since this function can handle an indefinite amount of arrays coming from the pipeline.
function Join-Array {
[CmdletBinding()]
param(
[parameter(ValueFromPipeline, Mandatory)]
[object[]] $InputObject,
[parameter(Mandatory)]
[string[]] $Columns
)
begin {
$inputDict = [ordered]@{}
$index = 0
}
process {
try {
if($MyInvocation.ExpectingInput) {
return $inputDict.Add($Columns[$index++], $InputObject)
}
foreach($item in $InputObject) {
$inputDict.Add($Columns[$index++], $item)
}
}
catch {
if($_.Exception.InnerException -is [ArgumentNullException]) {
$PSCmdlet.ThrowTerminatingError(
[Management.Automation.ErrorRecord]::new(
[Exception] 'Different count between input arrays and Columns.',
'InputArrayLengthMismatch',
[Management.Automation.ErrorCategory]::InvalidOperation,
$InputObject
)
)
}
$PSCmdlet.ThrowTerminatingError($_)
}
}
end {
foreach($pair in $inputDict.GetEnumerator()) {
$count = $pair.Value.Count
if($count -gt $max) {
$max = $count
}
}
for($i = 0; $i -lt $max; $i++) {
$out = [ordered]@{}
foreach($column in $inputDict.PSBase.Keys) {
$out[$column] = $inputDict[$column][$i]
}
[pscustomobject] $out
}
}
}
The usage would be pretty easy, the arrays can be passed through the pipeline:
$Array1 = 1, 2, 3
$Array2 = 'Joe Bloggs', 'John Doe', 'Jane Doe'
$Array3 = 'Yes', 'No'
$Array4 = 'hello', 'world', 123, 456
$Array1, $Array2, $Array3, $Array4 | Join-Array -Columns Number, Name, Valid, Test |
Export-Csv path\to\csv.csv -NoTypeInformation
Or via Named Parameter / Positional Binding:
Join-Array $Array1, $Array2, $Array3, $Array4 -Columns Number, Name, Valid, Test |
Export-Csv path\to\csv.csv -NoTypeInformation