一种方法是使用for loop https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_for?view=powershell-7.2.
$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
另一个例子使用function https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-7.2,逻辑或多或少是相同的,只是涉及更多开销,因为该函数可以处理来自管道的无限数量的数组。
function Join-Array {
[CmdletBinding()]
param(
[parameter(ValueFromPipeline, Mandatory)]
[object[]] $InputObject,
[parameter(Mandatory, Position = 0)]
[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]) {
$errorRecord = [Management.Automation.ErrorRecord]::new(
[Exception] 'Different count between input arrays and Columns.',
'InputArrayLengthMismatch',
[Management.Automation.ErrorCategory]::InvalidOperation,
$InputObject
)
$PSCmdlet.ThrowTerminatingError($errorRecord)
}
$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
}
}
}
使用起来非常简单,要加入/zip的数组可以通过pipeline https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipelines?view=powershell-7.2以及按位置定义的所需列名称:
$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 Number, Name, Valid, Test |
Export-Csv path\to\csv.csv -NoTypeInformation