Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hash tables in powershell

I'm developing an application in PowerShell. I am storing variables in a hashtable. How can I keep the order in the hashtable? I want the order to be the same as I when I filled the hashtable.

like image 330
RRR Avatar asked Nov 24 '10 08:11

RRR


People also ask

What are hash tables in PowerShell?

A hash table, also known as a dictionary or associative array, is a compact data structure that stores one or more key/value pairs. For example, a hash table might contain a series of IP addresses and computer names, where the IP addresses are the keys and the computer names are the values, or vice versa.

How do I create a hash table in PowerShell?

Using @{} Method You can use @{} method to create a hash table. Key-Value pair is separated with the Semi-Colon (;). You can only add unique keys. Duplicate keys are not accepted.

How do I print a hash table in PowerShell?

Printing hashtable: To print /display a hashtable, just type the variable name in which hashtable is saved. The above command displays a table with two columns, one for keys and the other one for the associated values for the keys.


2 Answers

Hash tables by nature don't maintain the order of values. There are a few workarounds already out on the net. Check these

http://www.tellingmachine.com/post/2009/01/When-PowerShell-hash-table-magic-backfires.aspx

http://huddledmasses.org/powershell-and-hashtable-oddities/

Or Try

PS C:\WINDOWS\system32> $OrderedList = New-Object System.Collections.Specialized.OrderedDictionary
PS C:\WINDOWS\system32> $OrderedList
PS C:\WINDOWS\system32> $OrderedList.Add("Name","Ravi")
PS C:\WINDOWS\system32> $OrderedList.Add("Age","30")
PS C:\WINDOWS\system32> $OrderedList

Name                           Value
----                           -----
Name                           Ravi
Age                            30
like image 112
ravikanth Avatar answered Oct 04 '22 23:10

ravikanth


PowerShell v3 will support ordered hashtables, using the [ordered] modifier. I suspect under the hood this is just a sortcut for using OrderedDictionary.

General v3 features overview: http://blogs.technet.com/b/windowsserver/archive/2012/05/30/windows-server-2012-powershell-3-0-and-devops-part-2.aspx

Specific illustration of using [ordered]: http://arcanecode.com/2012/06/04/powershell-v3-ordered-hashtables/

like image 31
piers7 Avatar answered Oct 04 '22 22:10

piers7