【问题标题】:How to add another property to the element of array based on mapping如何基于映射向数组元素添加另一个属性
【发布时间】:2021-11-11 05:48:44
【问题描述】:

在 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}

任何建议如何做到这一点? 如果数组是有属性的对象呢?

【问题讨论】:

    标签: arrays powershell object properties mapping


    【解决方案1】:

    看起来您使用Import-Csv 或其他东西获得了$Records 数组,因为您显示的是一个对象数组。

    这里最简单的做法是创建一个查找 Hashtable,将其作为汽车品牌与其制造商之间的映射:

    # 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 中显示为表格

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

    或者像以前一样:

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

    表格输出如下:

    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
    

    【讨论】:

    • 其实输入不是来自csv文件,而是来自查询结果的JSON,这有什么区别吗?
    • @GeorgiGochev 不,没有区别。这是 PowerShell 使用Write-Host 显示对象的默认字符串化方式。无论是从 JSON、CSV 还是 XML,您如何获得该数组都无关紧要
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2017-05-18
    • 2021-11-28
    • 2020-12-29
    • 1970-01-01
    相关资源
    最近更新 更多