Create a list of paired string values ββin PowerShell
For a project I am doing, I need to check and see if a couple of lines are present in a line from a file.
I tried to use a hash table like this:
$makes = 'Ferrari', 'Ford', 'VW', 'Peugeot', 'Subaru'
$models = 'Enzo', 'Focus', 'Golf', '206', 'Impreza'
$table = @{}
for ($i = 0; $i -lt $makes.Length; $i++)
{
$table.Add($makes[$i], $models[$i])
}
This works well until I try to insert a duplicate make. I quickly discovered that hash tables do not accept duplicates.
So, is there a way to create a double list of strings in PowerShell? It's very easy to do this in C #, but I haven't found a way to achieve it in PowerShell.
source to share
With minimal changes to your code and logic:
$makes = 'Ferrari', 'Ford', 'VW', 'Peugeot', 'Subaru'
$models = 'Enzo', 'Focus', 'Golf', '206', 'Impreza'
for ($i = 0; $i -lt $makes.Length; $i++){
[array]$cars += New-Object psobject -Property @{
make = $makes[$i]
model = $models[$i]
}
}
This uses a custom psobject
cast to array to resolve +=
.
source to share
Here's a way to avoid array concatenation (similar to Python's list comprehension syntax):
$makes = 'Ferrari', 'Ford', 'VW', 'Peugeot', 'Subaru'
$models = 'Enzo', 'Focus', 'Golf', '206', 'Impreza'
$cars = 0..$makes.Length | ForEach-Object {
[PSCustomObject] @{
Make = $makes[$_]
Model = $models[$_]
}
}
source to share
Note. The question asked - creating a list of value pairs regardless of duplicates - is most effectively answered by Bill Stewart's answer .
This answer focuses on a hash table solution that collects all models for a given brand into a single record and provides efficient search for models by brand.
You can still use a hash table - with its handy key-based searches - if you store all the models associated with a given brand as an array in each brand - by definition one single - entry :
# Note the duplicate 'VW' entry at the end. $makes = 'Ferrari', 'Ford', 'VW', 'Peugeot', 'Subaru', 'VW' # Corresponding models. $models = 'Enzo', 'Focus', 'Golf', '206', 'Impreza', 'Polo' $table = [ordered] @{}; $i=0 # [ordered] (PSv3+) preserves the order of the keys foreach($make in $makes) { # Add the model at hand to the make array of models. # The entry is created on demand as an array, due to [array] # (which creates an [object[]] array), # and for additional models the array is appended to. # You could also use [string[]], specifically. [array] $table[$make] += $models[$i++] } # Output the resulting hashtable $table
This gives:
Name Value ---- ----- Ferrari {Enzo} Ford {Focus} VW {Golf, Polo} Peugeot {206} Subaru {Impreza}
Note that the value VW
has 2 entries ( {...}
indicates that the value is an array).
To get this model (s) later, just use:
$vwModels = $table['VW']
To check if a given manufacturer / model pair is contained in the table:
$table[$make] -contains $model
source to share