Hash Table

by shawnwat at 2012-12-18 17:59:36

So for some reason I just don’t get Hash Tables. Anyone have suggestions on reading help me understand using them?
by iHunger at 2012-12-18 19:20:34
Do you not understand what a hash table is, how to use one, or why to use one?
by nohandle at 2012-12-19 06:43:22
On high level you can imagine hash table as one dimensional array that is indexed by keys (names) instead of numbers.
So instead of $array[0] you do $hash["name"] (or $hash.name if you use another more common notation EDIT: This notation cannot be used on arrays.)

The hash table consists of key=value pairs. The syntax is @{key="value";anotherkey="anothervalue"}. The keys has to be unique in the hashtable, the values do not.
In powershell you don’t often use the hashtable for what it was created - getting data quickly from large lists - you rather use it to create list of relations , like property=value when creating a new object.
There is no magic in it, the syntax looks wierd but in result you just create named boxes that has some values in them.
by shawnwat at 2012-12-19 13:47:51
Great explenation above, i guess now I want to know the how and why you would use it.
by nohandle at 2012-12-20 00:47:02
1] creating set of propertyname=value pairs to create new object:
#you can separate the pairs by ; or by newline
$hash = @{
FirstName="John"
LastName="Doe"
}
#create new object
$object = New-Object -TypeName PSObject -Property $hash
$object


2] create new object using select-object and special hashtable in format
name="propertyname"
expression={scriptblock that returns value of the expression}
you can also shorten to n and e

#fl for format-list because the fullname won't show because of the limitations of the format-table
$Object | select *, @{n="FullName"; e={$.FirstName + " " + $.LastName}} | fl


this is useful when you add new columns to existing object and calculate the values from the existing properties.

3] any general purpose where you need to maintain key=value realtions

4] saving configuration within the script without using xml, and without creating tons of variables like $configLogTxtLog
$configuration = @{
Logging = @{
textLog = "c:\temp\log.log"
dbLog= "server\sql"
}
}
$configuration.Logging.textLog
by shawnwat at 2013-01-06 19:54:14
Good example of using the hash table is: http://jdhitsolutions.com/blog/2013/01/ … ash-table/
I also thought of a slightly different description from above. So instead of $array[0] you have $hash["name"] which would be the primary key in MS Access DB.