What is the best way to convert a List to a Hashtable?
Say I have a list like ("Key",$value,"Key2",$value2)
What is the shortest syntax to convert it into a Hashtable?
To create a hash table in PowerShell, you'll use an @ symbol followed by an opening curly brace and a closing curly brace as shown below. Here you can see my hash table is now three lines with a key/value pair in the middle. It can also be represented on one line as well.
The key/value pairs might appear in a different order each time that you display them. Although you cannot sort a hash table, you can use the GetEnumerator method of hash tables to enumerate the keys and values, and then use the Sort-Object cmdlet to sort the enumerated values for display.
GetEnumerator in PowerShell is used to iterate through the Hashtable or array to read data in the collection. GetEnumerator doesn't modify the collection data. Use foreach or foreach-object in PowerShell to iterate over the data read from the GetEnumerator.
You can also use the Hashtable method called Add() to add the value. The format is as below. To remove the Key-value from the Hashtable, you need to use the Remove(Key) method.
Try the following
$table = new-object System.Collections.Hashtable
for ( $i = 0; $i -lt $list.Length; $i += 2 ) {
$table.Add($list[$i],$list[$i+1]);
}
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