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.
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}
$ComponentTobeBuild.GetEnumerator() | ? { $_.Value -eq "True" }
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.
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
You could also use the Dictionary.Keys' Where method which returns all elements where a condition holds true. That condition could be a lambda asserting that the tested key $_ relates to a "True" value in the dictionary.
$ComponentTobeBuild=@{"ComponentNameX"="True";
"ComponentNameXyz"="False";
"SomeComponent"="False"}
$ComponentTobeBuild.Keys.Where({$ComponentTobeBuild[$_] -eq "True"})
# -> @("ComponentNameX")
来源:https://stackoverflow.com/questions/11357654/how-to-get-hash-table-key-which-has-specific-value