如何根据映射向数组元素添加另一个属性

How to add another property to the element of array based on mapping

在 Powershell 中我有以下数组

foreach ($Record in $Records)
{ write-host $Record
}

@{car=OPEL; count=3}
@{car=BMW; count=2}
@{car=OPEL; count=8}
@{car=AUDI; count=3}
@{car=FORD; count=5}
@{car=FORD; count=4}
@{car=OPEL; count=4}
@{car=AUDI; count=5}
@{car=BMW; count=3}

我想为数组中的每个元素添加另一个 属性,这应该是 属性 "car"

的直接映射
car     manufacturer
OPEL    GM
BMW     Bayerishe Motoren Werke
AUDI    Volkswagen group
FORD    FORD Motor Company

依此类推,制造商列表有100多个不同的值,初始数组应该变成

@{car=OPEL; count=3; manufacturer=GM}
@{car=BMW; count=2; manufacturer=Bayerishe Motoren Werke}
@{car=OPEL; count=8; manufacturer=GM}
@{car=AUDI; count=3; manufacturer=Volkswagen group}
@{car=FORD; count=5; manufacturer=FORD Motor Company}
@{car=FORD; count=4; manufacturer=FORD Motor Company}
@{car=OPEL; count=4; manufacturer=GM}
@{car=AUDI; count=5; manufacturer=Volkswagen group}
@{car=BMW; count=3; manufacturer=Bayerishe Motoren Werke}

有什么建议可以实现吗? 如果数组是具有属性的对象怎么办?

看起来您使用 Import-Csv 或其他方法获得了 $Records 数组,因为您显示的是 objects.

的数组

这里最简单的事情是创建一个查找哈希table,作为汽车品牌与其制造商之间的映射:

# create a mapping lookup Hashtable
$map = @{
    'OPEL' = 'GM'
    'BMW'  = 'Bayerishe Motoren Werke'
    'FORD' = 'FORD Motor Company'
    'AUDI' = 'Volkswagen Group'
}
# use the $map to add a new property to each of the records
foreach ($Record in $Records){ 
    $Record | Add-Member -MemberType NoteProperty -Name 'manufacturer' -Value $map[$Record.car]
}

现在您可以将此 $Records 数组保存回例如 CSV 文件

$Records | Export-Csv -Path 'X:\CarsAndManufacturers.csv' -NoTypeInformation

在屏幕上或在 GridView 中显示为 table

$Records | Format-Table -AutoSize  # or: $Records | Out-GridView

或者像以前一样:

foreach ($Record in $Records) { 
    Write-Host $Record
}

Table 的输出如下所示:

car  count manufacturer           
---  ----- ------------           
OPEL 3     GM                     
BMW  2     Bayerishe Motoren Werke
OPEL 8     GM                     
AUDI 3     Volkswagen Group       
FORD 5     FORD Motor Company     
FORD 4     FORD Motor Company     
OPEL 4     GM                     
AUDI 5     Volkswagen Group       
BMW  3     Bayerishe Motoren Werke