When I execute the command:
$var = @{a=1;b=2}
in Powershell (Version 3), $var
ends up with a value of {System.Collections.DictionaryEntry, System.Collections.DictionaryEntry}
. Why is this happening? How can I store the values I want to store?
That's because your ISE is enumerating the collection to create the variable-treeview, and the objects returned from a HashtableEnumerator
which you get from $var.GetEnumerator()
are DictionaryEntry
-objects.
$var = @{a=1;b=2}
#Collection is a Hashtable
$var | Get-Member -MemberType Properties
TypeName: System.Collections.Hashtable
Name MemberType Definition
---- ---------- ----------
Count Property int Count {get;}
IsFixedSize Property bool IsFixedSize {get;}
IsReadOnly Property bool IsReadOnly {get;}
IsSynchronized Property bool IsSynchronized {get;}
Keys Property System.Collections.ICollection Keys {get;}
SyncRoot Property System.Object SyncRoot {get;}
Values Property System.Collections.ICollection Values {get;}
#Enumerated objects (is that a word?) are DictionaryEntry(-ies)
$var.GetEnumerator() | Get-Member -MemberType Properties
TypeName: System.Collections.DictionaryEntry
Name MemberType Definition
---- ---------- ----------
Name AliasProperty Name = Key
Key Property System.Object Key {get;set;}
Value Property System.Object Value {get;set;}
Your value (1 and 2) is stored in the Value
-property in the objects while they Key
is the ID you used (a and b).
You only need to care about this when you need to enumerate the hashtable, ex. When you're looping through every item. For normal use this is behind-the-scenes-magic so you can use $var["a"]
.