Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of key value pairs to a hashtable

Tags:

powershell

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?

like image 693
Scott Weinstein Avatar asked Oct 20 '09 15:10

Scott Weinstein


People also ask

How do I create a Hashtable in PowerShell?

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.

How do I get key value pairs in PowerShell?

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.

What is GetEnumerator in PowerShell?

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.

How do I add values to a Hashtable in PowerShell?

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.


1 Answers

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]);
}
like image 113
JaredPar Avatar answered Sep 17 '22 15:09

JaredPar