count with a hashtable then count again

At this point, its just standard code – create an empty hashtable, get an entry, check to see if the key exists.  If not, add the key and #1.  If it does, add the value + 1 to the key.  At the end, you have a set of keys and a count for each one.  Probably should write a module for that and save time.

of course you know you can getenumerator on the hash, and sort and retrieve the keys and values (or just the values if that is what you want).

Recently, working with Active Directory and groups, i’ve been doing something different – if the key doesn’t exist, add the key and the value (which is typically a name).  If it does exist, increment the value by getting the old value and appending the new value with a suitable delimiter (“,”,”|”).  Down the line, we get the key and split the value to put multiple members into a group called ‘key’.

The hash part looks like this:

$list= (Get-Content "\\path_to_file\file.txt"|select -skip 1)
$hash = @{} 
 foreach ($a in $list){
 $array = $a.Split("|")
 $key = $array[0]
 $value= $array[1]
 $hash.Set_Item($key, $hash[$key] + "," + $value)
 } else {
 } # end if/else
 } # end foreach

I was getting some really odd numbers ranging from 1 to 352. In point of fact, these were the number of advisees for a given advisor and 352???

$hash would dump the key (the advisor) and the value – which was a comma separated list of advisees.  Didn’t want to count the numbers on the screen and they would run off into … anyway.  I tried to use $value.length and with the enumerator did get data – but it was even worse.  Of course, the length of a string is NOT the number of entries, so that was just a mistake.

Finally, this code got me what i was trying to get – a sorted list of the number of advisees for each advisor.  It could be better written, but it worked and i could go on to something else.

$count = @()
$ad = $hash.getenumerator()
$ad | foreach-object { 
$array = ($_.value).split(",")
$count += $array.count
$b = $count|sort-object
This entry was posted in Uncategorized. Bookmark the permalink.