在哈希表中搜索一个键并平均关联值Powershell

在哈希表中搜索一个键并平均关联值Powershell,powershell,Powershell,所以我有一个脚本,我试图获取测试名并将其作为键存储到哈希表中,然后获取一个高测试分数和一个低测试分数,并将这2个作为值存储。然后,我想获取并允许用户搜索测试名称,并查看高分和低分。我目前拥有的是: $testInfo = @{} $testName = read-host "Please enter the name of the test" $testHigh = read-host "Please enter the high score of the test" $testLow = re

所以我有一个脚本,我试图获取测试名并将其作为键存储到哈希表中,然后获取一个高测试分数和一个低测试分数,并将这2个作为值存储。然后,我想获取并允许用户搜索测试名称,并查看高分和低分。我目前拥有的是:

$testInfo = @{}
$testName = read-host "Please enter the name of the test"
$testHigh = read-host "Please enter the high score of the test"
$testLow = read-host "Please enter the low score of the test"
$testInfo.Add($testName, $testHigh + " " + $testLow
$search = read-host "Please enter the name of the test you'd like to view the average score of"

这段代码成功地将高分和低分存储到该测试名称中,但我需要一种方法来查找带有$search值的测试名称。然后将存储在值部分的两个测试分数取平均值。

这取决于您想如何使用它,但有几种方法:

$testInfo.ContainsKey($search)
如果密钥存在,将返回
$true
/
$false

您还可以遍历这些键:

foreach($testInfo.Keys.GetEnumerator()中的key){
$key
}
你可以参考它:

$testInfo[$search]
#或
$testInfo.$search

您可以选择最适合您需要的引用/使用方式。

根据您的要求,使用嵌套哈希表或自定义对象更容易实现这一点。对于嵌套哈希表,需要将测试分数添加为测试名称值的附加哈希表。之后,您将循环通过所有关键点进行匹配的关键点搜索,然后创建一个平均值

由于测试分数值保存为字符串,因此将$avg变量定义为整数非常重要

$testInfo = @{}
$testName = read-host "Please enter the name of the test"
$testHigh = read-host "Please enter the high score of the test"
$testLow = read-host "Please enter the low score of the test"
$nest = @{High=$testHigh; Low=$testLow}
$testInfo.Add($testName, $nest)
$search = read-host "Please enter the name of the test you'd like to view the average score of"
$avg = 0
$count = 0
$testInfo[$search].GetEnumerator() | % { $avg += $_.value; $count++ }
Write-Host "The average score for test $search is $($avg/$count)."
我包括了一个计数,但是如果你只想输入2个值,那么这个计数可以被删除