Search code examples
listpowershellhashtable

Create a list of paired string values in PowerShell


For a project I am doing, I need to check and see if a pair of strings are present in a line from a file.

I have 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 found out that hash tables do not accept duplicates.

So is there a way of creating a double list of strings in PowerShell? It is very easy to do in C# , but i have found no way of achieving it in PowerShell.


Solution

  • 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 custom psobject, cast to an array so that += is allowed.