Hash Tables GetEnumerator method

#Instead of posting a large hash table the following generates a small one
$hash = @{}
for ($i=1; $i -le 20; $i++)
	$date = (get-date).AddDays((Get-Random -Minimum 1 -Maximum 365));
	$delay = (Get-Random -Minimum 1 -Maximum 30)
	$hash[$i] = @{delay = $delay; Date = $date}

#Working with the hash table

$var = $hash.GetEnumerator()

$var #displays the rows of the hash table
$var #empty? Not what I was expecting
$var.GetType().name #HashtableEnumerator
$var | gm #error: gm : You must specify an object for the Get-Member cmdlet.

$var = $hash.GetEnumerator()
$var | gm #works
$var | gm #errors

$var = $hash.GetEnumerator()
$try = $var
$try | gm
$var | gm #error: gm : You must specify an object for the Get-Member cmdlet.

I’m not sure why viewing the data clears the data. Could someone shed some insight? Thank you.

Worked it out.

Hashtable.GetEnumerator Method Returns an IDictionaryEnumerator that iterates through the Hashtable. When displaying a variable the IDictionaryEnumerator Interface uses MoveNext to advance the enumerator to the next element of the collection. This can be mitigated by using the reset method to set the enumerator to its initial position.

$var = $hash.GetEnumerator()
$var | gm #works
$var | gm #errors
$var | gm #works

I am not sure exactly what you are trying to do but if you want to fill out a table then you should use the add method for the hash table rather than trying to access with the array index

if($hash.$delay -eq $null) { #check to see that the key or name does not already exist
} This does not take care of duplicate entries for the same $delay value

I hope this helps. Also see Bruce Payette’s Windows PowerShell in action 2nd edition and/or http://msdn.microsoft.com/en-us/library/system.collections.hashtable.add(v=vs.110).aspx

Thanks for the reply Rich; I was working on a logging hash table and wasn’t fully understanding my results with IDictionaryEnumerator until I reread the documentation (thus both the question and solution above).

I’ve not seen a difference in populating a hash table using $hash[$i] vs $hash.add($i), as in my testing with large tables Measure-Command results are almost identical.