Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get hash table key which has specific value?

Tags:

I am having a hash table where Keys are being used based on value.

For ex.

    $ComponentTobeBuild=@{"ComponentNameX"="True";                           "ComponentNameXyz"="False";                           "SomeComponent"="False"} 

I would like to get the keys which are having values True. (I will pass the key to some other script as parameter).

I was trying like that , But i think some where i am missing as it is not listing the keys.

$($ComponentToBuild.Keys) | Where-Object { $_.Value -eq "True" } 

How to get the component Name which are having denoted as True? Also i would like to know whether hash table is a wise choice for this kind of work. Because I thought that Hash table will be mainly be used for processing the values.

like image 957
Samselvaprabu Avatar asked Jul 06 '12 07:07

Samselvaprabu


People also ask

Can we get key from value in Hashtable?

The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

How do I find the value of a hash table?

Hashtable. containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the Hashtable. It takes the Value as a parameter and returns True if that value is mapped by any of the keys in the table.

How do I get key value pairs in PowerShell?

The key/value pairs might appear in a different order each time that you display them. Although you cannot sort a hash table, you can use the GetEnumerator method of hash tables to enumerate the keys and values, and then use the Sort-Object cmdlet to sort the enumerated values for display.

Do hash table keys have to be unique?

A hash table is an unordered collection of key-value pairs, where each key is unique. Hash tables offer a combination of efficient lookup, insert and delete operations.


2 Answers

$ComponentTobeBuild.GetEnumerator() | ? { $_.Value -eq "True" } 
like image 119
David Brabant Avatar answered Nov 16 '22 11:11

David Brabant


Hi this should work for what you want.

$ComponentTobeBuild=@{"ComponentNameX"="Test";                           "ComponentNameXyz"="False";                           "SomeComponent"="False"}                      Foreach ($Key in ($ComponentTobeBuild.GetEnumerator() | Where-Object {$_.Value -eq "Test"})) {$Key.name} 
like image 22
justinf Avatar answered Nov 16 '22 11:11

justinf