在我的foreach中,我想对另一个对象变量进行where对象过滤。
具体来说,下面是我的对象数组的两个实例($ arrayCounts):
[0]: [Hastable: 2]
[0]: [Occurences, 6]
Key: "Occurences"
Value: 6
[1]: [Ip, "10.10.10.10"]
Key: "Ip"
Value: "10.10.10.10
[1]: [Hastable: 2]
[0]: [Occurennces, 3]
Key: "Occurences"
Value: 3
[1]: [Ip, "10.10.10.11"]
Key: "Ip"
Value: "10.10.10.11"
这是我要执行where-object的循环:
foreach ($result in $resultHash.GetEnumerator()) {
$currentCountResultObject = @{
Ip = $result.Key
Legitimacy = $result.Value
Occurences = $arrayCounts.Occurences.Value | Where-Object ($result.Key -eq $arrayCounts.Ip.Value)
}
$countResultObject += $currentCountResultObject
}
“ Ip”和“ Legitimacy”成员已经很好地完成了工作,但是由于我的错误的where-object表达式,“出现次数”保持为空。
预期的输出是:
[0]: [Hastable: 3]
[0]: [Legitimacy, "legitimate"]
Key: "Legitimacy"
Value: "legitimate"
[1]: [Ip, "10.10.10.10"]
Key: "Ip"
Value: "10.10.10.10"
[2]: [Occurences, 3]
Key: "Occurences"
Value: 3
[1]: [Hastable: 3]
[0]: [Legitimacy, "unknown"]
Key: "Legitimacy"
Value: "unknown"
[1]: [Ip, "10.10.10.11"]
Key: "Ip"
Value: "10.10.10.11"
[2]: [Occurences, 28]
Key: "Occurences"
Value: 28
where对象的目的是为每个IP给出出现的次数,并且此信息仅在我的变量$ arrayCounts中可用(在我当前的foreach管道之外)。
我希望我足够清楚。
在此先感谢您的帮助!
看来您想$arrayCounts
通过哈希表数组中Ip
的$resultHash
哈希表条目值来交叉引用数组中的哈希表。
根据您的代码,该Where-Object
命令应如下所示:
Occurrences = ($arrayCounts | Where-Object { $_.Ip -eq $result.Key }).Occurrences
也就是说,您必须枚举array的元素($arrayCounts
即哈希表),并对照Ip
手头的IP地址检查每个哈希表的条目。此过滤操作的结果是匹配的哈希表(我假设Ip
条目在输入哈希表中是唯一的),Occurrences
然后其条目值包含所需的出现次数。
通常,使用.Where()
数组方法代替Where-Object
cmdlet可以加快操作速度,但这也是因为它允许您在找到匹配项后停止过滤(参数'First'
):
Occurrences = ($arrayCounts.Where({ $_.Ip -eq $result.Key }, 'First')).Occurrences
但是,基于期望的输出,我怀疑您对$resultHash
变量的枚举是有缺陷的。假设它也是一个哈希表数组,那么您的代码将如下所示:
# Array of sample reference hashtables.
$arrayCounts =
@{ Occurrences = 6; Ip = "10.10.10.10" },
@{ Occurrences = 3; Ip = "10.10.10.11" }
# Array of sample result hashtables
$resultHashes =
@{ Legitimacy = 'legitimate'; Ip = "10.10.10.10" },
@{ Legitimacy = 'unknown'; Ip = "10.10.10.11" }
# Loop over the hashtables in $resultHashes, construct a new hashtable
# with the cross-referenced information for each, and collect the
# result in a new hashtable array.
$finalResultHashes =
foreach ($resultHash in $resultHashes) {
# Output a hashtable with that includes the matching Occurrence value
# from the $arrayCounts array based on this result's IP.
@{
Ip = $resultHash.Ip
Legitimacy = $resultHash.Legitimacy
Occurrences = ($arrayCounts.Where({ $_.Ip -eq $resultHash.Ip }, 'First')).Occurrences
}
}
# Output the results for display.
# Note: I'm using JSON only for illustrative purposes.
$finalResultHashes | ConvertTo-Json
以上收益(JSON仅用于阐明结果结构):
[
{
"Legitimacy": "legitimate",
"Ip": "10.10.10.10",
"Occurrences": 6
},
{
"Legitimacy": "unknown",
"Ip": "10.10.10.11",
"Occurrences": 3
}
]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句