powershelltypeshashtableint32

How to specify data type for hashtable?


It seems PowerShell hashtable (@{}) is map of string→string by default. But I wish that my value type is Int32 so that I could do calculation on it.

How could I specify the type information when declaring a hashtable variable?


Solution

  • Hashtables map keys to values. The type of the keys and values is immaterial.

    PS C:\> $ht = @{}
    PS C:\> $ht[1] = 'foo'
    PS C:\> $ht['2'] = 42
    PS C:\> $ht
    
    Name                           Value
    ----                           -----
    2                              42
    1                              foo
    
    PS C:\> $fmt = "{0} [{1}]`t-> {2} [{3}]"
    PS C:\> $ht.Keys | % {$fmt -f $_, $_.GetType().Name, $ht[$_], $ht[$_].GetType().Name}
    2 [String]      -> 42 [Int32]
    1 [Int32]       -> foo [String]

    If you have an integer in a string and want to assign that as an integer, you can simply cast it on assignment:

    PS C:\> $ht[3] = [int]'23'
    PS C:\> $ht.Keys | % {$fmt -f $_, $_.GetType().Name, $ht[$_], $ht[$_].GetType().Name}
    2 [String]      -> 42 [Int32]
    3 [Int32]       -> 23 [Int32]
    1 [Int32]       -> foo [String]