I use hashtables ALOT – especially to generate counts or lists of values associated with a unique key.

Something like

if($hash.containskey($mykey))
{
$hash.Set_Item($mykey, $hash[$mykey] + 1)
}
else
{
$hash.add($mykey,1))
} # end if/else

$hash will (shortly) contain a list of keys and their count.  You can put other things in as well.

This post by mjolinor is truly great for that (and there is more)

$hash = @{}
foreach ($a in $b) {$hash[$a]++}

This should create an entry with 1 if it doesn’t exist or with value + 1 if it does.  Sweet.

But remember that a hashtable can contains objects, or arrays.  So the value of the entry for a key is a list – or array, we can add to it like this

$hash[$course_section] += @($course_student)

and of course the value of $hash[$course_section] , so we can foreach over it without messing around.

In the comments to the reference was a suggestion to create a blank hashtable with names as placeholders like so

$myhash=@{Name=”;Prop1=”;prop2=”}.  You can then add values as you need, or append values into arrays for each key.

Advertisements
Link | This entry was posted in powershell. Bookmark the permalink.