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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With