如何枚举哈希表作为键值对/按键值集合过滤哈希表 [英] How can I enumerate a hashtable as key-value pairs / filter a hashtable by a collection of key values
问题描述
编者注:
这个问题的历史很复杂,但可以归结为:
*要了解如何通过键值对 来枚举哈希表的条目,请参见其他答案.
Editor's note:
This question has a complicated history, but boils down to this:
* To learn how to enumerate the entries of a hashtable by its key-value pairs, see the accepted answer.
* To learn how to filter a hashtable by a collection of key values, see the other answer.
我想我又陷入了X Y问题,最初的问题是关于过滤哈希表.我发现在创建哈希表之前进行过滤比较容易.问题回答了吧?
I think I fell into the X Y problem again, my initial question was about Filtering a hash table. I discovered it's easier to filter before creating the hash table. Question answered, right?
不是,Y问题是循环每个键并使用@briantist帮助我的值.
Nope, the Y problem was looping each Key and using the Values which @briantist helped me with.
我的目标是遍历关键字名称(即时间戳),并使用关键字名称作为任务名称和触发器来安排任务.
My goal is to loop over the key names, which are timestamps, and schedule a task using the key name as the task name and trigger.
我正在使用Group-Object -AsHashTable -AsString
-edit从CSV文件创建哈希表,在这里值得一提的是,在创建HashTable之前过滤CSV仅使Pipeline
或脚本上的事情变得容易 >.
I'm creating a hash table from a CSV file using Group-Object -AsHashTable -AsString
-edit, it's worth mentioning here that filtering the CSV before creating the HashTable only makes things easier down the Pipeline
or script.
例如:
Import-CSV (ls -path D:\ -Filter source*.csv | sort LastWriteTime | Select -Last 1).FullName |
where {$_.TimeCorrected -ne 'ManualRebootServer'} |
group TimeCorrected -AsHashTable -AsString
我正在尝试遍历键名,并能够使用以下命令显示键名:
I'm trying to loop over the key names and able to display the key names using:
$var = Import-Csv csv123.csv | Group-Object Value1 -AsHashTable -AsString
foreach ($key in $var.Keys){"The key name is $key"}
#Create a scheduled task named and triggered based on the HashTable keyname
#test test test
foreach ($key in $var.keys){IF($key -ne 'ManualRebootServer'){"Register-ScheduledJob"}}
我只是不确定如何从我感兴趣的键中获取值.
I'm just not sure how to get the values from the keys I am interested in.
我找到了以下作品,但仅当我手动输入密钥名称时才可以.我只是不确定如何组合两个循环.
I've found the following works, but only when I enter a Key name manually. I'm just unsure how to combine both loops.
($val.GetEnumerator() | Where {$_.key -eq '06-11-16 18:00'} | ForEach-Object { $_.value }).Server
推荐答案
您在这里有一些选择.
通过键枚举:
foreach ($key in $var.Keys) {
$value = $var[$key]
# or
$value = $var.$key
}
枚举键值对(您已经发现,但可能没有有效使用):
Enumerating key-value pairs (which you've discovered, but may not be using effectively):
foreach ($kvp in $var.GetEnumerator()) {
$key = $kvp.Key
$val = $kvp.Value
}
这篇关于如何枚举哈希表作为键值对/按键值集合过滤哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!