Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 264
AJennings1 Avatar asked May 24 '17 09:05

AJennings1


People also ask

How do I make a list of strings in PowerShell?

Create an Array of Strings in PowerShell Using the @() Method. Another method to create an array of strings in PowerShell is the “@()” method. Define your array name, and store its sting values within the () brackets after the “@” symbol.

How do I create a string array in PowerShell?

To create a string array, we can declare the variable name. Another way is to create using the @(). One more way is by creating the system. collections.

How do you create an array of variables in PowerShell?

To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.


1 Answers

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.

like image 158
G42 Avatar answered Sep 20 '22 23:09

G42