How to get hash table key which has specific value?

I know this is old, but I saw this on my search for an other problem and wondered why you bother with Enumerators. Just build the code exactly as the question in real language:

Give me all keys, where the value is 'True'.

$ComponentTobeBuild.Keys | ? { $ComponentTobeBuild[$_] -eq 'True'  }

For sake of consistency I would encapsulate that in @() to get an Array even if there is just one or no result.

As for the Solution the asker had, the problem is that $_ is a String and .Value is not the value of the key. It simply doesn't exist in a String. You have to get the value of the hashtable with $_ as Key in order to compare it.


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}

The problem with filtering Hashtables in PowerShell is that you can't iterate over the Key-Value pairs.

Let's say you have some collection:

$collection = @{ 
    a = 'A'; 
    b = 'B'; 
    c = 'C'; 
    d = 'D'; 
    e = 'E';
    ...
}

You would expect to be able to use

$results = $collection | Where-Object { $_.Key -in ('a', 'b', 'd') }

in PowerShell, but that's not possible.

Therefore you have fall back to using the enumerator:

$results = $collection.GetEnumerator() | Where-Object { $_.Key -in ('a', 'b', 'd') }
$results

Name                           Value
----                           -----
d                              D
b                              B
a                              A

$ComponentTobeBuild.GetEnumerator() | ? { $_.Value -eq "True" }