Question:
I am playing around with hashtables in powershell and try to figure out, if there is a way, to show the content of Key1 (not the value).
I tried several ways to have as an result “Monday” but either I get all the names of the table, a blank return or an error message.
here’s my table:
1 2 |
$Weekdays = @{Monday = 'Montag';Tuesday = 'Dienstag'} |
If possible, I would like to have as an output only “Monday”, is there a way, I can enter code to have “Monday” as an output?
Thank you very much for your help,
Mike
Answer:
You can access the Key/ValueCollection inside the hashtable:
1 2 3 4 |
$Weekdays = @{Monday = 'Montag';Tuesday = 'Dienstag'} echo $($Weekdays.Keys)[0] echo $($Weekdays.Values)[1] |
will return
1 2 3 |
Monday Dienstag |
enclosing the call to “Keys” in $() will result in the Collection being converted to an Object Array, as you ca see here:
1 2 3 4 |
$Weekdays = @{Monday = 'Montag';Tuesday = 'Dienstag'} $Weekdays.Keys.Gettype() $($Weekdays.Keys).Gettype() |
which gives
1 2 3 4 5 |
IsPublic IsSerial Name BaseType -------- -------- ---- -------- False True KeyCollection System.Object True True Object[] System.Array |
and an object array can be indexed into with integers.