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

Time:09-17

In Powershell I have the following array

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}

I want to add another property of each element in the array, which should be direct mapping from property "car"

car     manufacturer
OPEL    GM
BMW     Bayerishe Motoren Werke
AUDI    Volkswagen group
FORD    FORD Motor Company

and so on, the list with manufacturers has over 100 different values, and the inital array should become

@{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}

Any suggestions how to accomplish this? What if the array is object with properties?

CodePudding user response:

Looks like you obtained the $Records array using Import-Csv or something, as what you show is an array of objects.

The easiest thing to do here is to create a lookup Hashtable that servers as a mapping between the car brand and its manufacturer:

# 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]
}

Now you can save this $Records array back to for instance a CSV file

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

Display as table on screen or in a GridView

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

Or as you did before:

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

Output as Table looks like this:

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
  • Related