如果你的数组有 objects 就像你说的那样
$array1 = [PsCustomObject]@{Id=1; Count=24},
[PsCustomObject]@{Id=2; Count=34}
$array2 = [PsCustomObject]@{Id=1; Name="Some name"},
[PsCustomObject]@{Id=2; Name="Some other name"}
你可以这样做:
# this updates the objects in $array1
foreach ($item in $array1) {
foreach ($obj in $item) {
$obj | Add-Member -MemberType NoteProperty -Name 'Name' -Value ($array2 | Where-Object { $_.Id -eq $obj.Id }).Name
}
}
# show on screen
$array1
# export to CSV
$array1 | Export-Csv -Path 'D:\Test\Joined.Csv' -NoTypeInformation
屏幕输出:
Id 计数名称
-- ----- ----
1 24 一些名字
2 34 其他名称
如果数组存储 Hashtables 喜欢
$array1 = @{Id=1; Count=24},
@{Id=2; Count=34}
$array2 = @{Id=1; Name="Some name"},
@{Id=2; Name="Some other name"}
然后使用这个:
# this returns a new array of PSObjects
$result = foreach ($item in $array1) {
foreach ($hash in $item) {
$hash['Name'] = ($array2 | Where-Object { $_.Id -eq $hash.Id }).Name
}
[PsCustomObject]$hash
}
# show on screen
$result
# export to CSV
$result | Export-Csv -Path 'D:\Test\JoinedFromHashes.Csv' -NoTypeInformation
屏幕输出:
名称 ID 计数
---- -- -----
一些名字 1 24
其他名称 2 34
请注意,哈希表默认是无序的,因此列出现的顺序可能会有所不同