Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Hashtable show first key

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:

$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

like image 793
Mike Avatar asked Aug 21 '19 15:08

Mike


Video Answer


2 Answers

You can access the Key/ValueCollection inside the hashtable:

$Weekdays = @{Monday = 'Montag';Tuesday = 'Dienstag'}    
echo $($Weekdays.Keys)[0]
echo $($Weekdays.Values)[1]

will return

Monday
Dienstag

enclosing the call to "Keys" in $() will result in the Collection being converted to an Object Array, as you ca see here:

$Weekdays = @{Monday = 'Montag';Tuesday = 'Dienstag'}
$Weekdays.Keys.Gettype()
$($Weekdays.Keys).Gettype()

which gives

IsPublic IsSerial Name                                     BaseType                                                                                                                     
-------- -------- ----                                     --------                                                                                                                     
False    True     KeyCollection                            System.Object                                                                                                                
True     True     Object[]                                 System.Array  

and an object array can be indexed into with integers.

like image 194
Oliver Avatar answered Sep 21 '22 10:09

Oliver


$Weekdays = @{Monday = 'Montag';Tuesday = 'Dienstag'}

$Weekdays["Monday"] will print out Montag. it is like Arry with index. In Hashtable/Dictionary the key is the index. Definitely remember to put the key in quote. Otherwise it will fail.

like image 29
Abul Ahmed Avatar answered Sep 20 '22 10:09

Abul Ahmed