因此,如果您查看下面的代码,我会在用户输入一个人的姓名,地址,城市,州和邮政编码。然后我用这个名字创建一个带有CreateKey函数的键,它接受它们的名字,将它分开,然后取第一个字母和第二个字母和第一个和最后一个字母的最后一个字母。然后我将其设置为哈希表的关键基础,然后创建名为$ hash的哈希表。然后它接受该键并将地址键设置为等于函数+" ADD"中创建的键。然后将为地址输入的值存储到$ hash字典中,其余部分也是如此。因此,在获得所有这些值之后,如何进行搜索以搜索包含从该函数创建的密钥的键。因此,如果我想查找Brandon Gandy,它会查找包含" ROAD"的所有键,这是该函数为具有该特定名称的键创建的。有人有想法吗?
$count = 1
$key = ""
$hash = @{}
$searchKey = ""
Function CreateKey($name){
$split = $name -split " "
$first = $split[0]
$last = $split[1]
$arrayLen = $split.Length
if ($arrayLen -gt 2)
{
$last = $split[$arrayLen-1]
}
$f = $first[1]
$fl = $first[$first.Length-2]
$l = $last[1]
$ll = $last[$last.Length-2]
$key = $f + $fl + $l + $ll
$key = $key.ToUpper()
return $key
}
Write-host "This program will ask the user for the names and \n some other information about these people!"
while ($count -lt 3){
$name = Read-Host "Please enter the name of person $count"
$address = Read-Host "Please enter the address of person $count"
$city = Read-Host "Please enter the city of person $count"
$state = Read-Host "Please enter the state of person $count"
$zip = Read-Host "Please enter the zip of person $count"
$key = CreateKey $name
$hash[$key] = $name
$hash[$key + "ADD"] = $address
$hash[$key + "CIT"] = $city
$hash[$key + "STA"] = $state
$hash[$key + "ZIP"] = $zip
write-host ($hash | out-string)
$name = ""
$adress = ""
$city = ""
$state = ""
$zip = ""
$count++
}
$search = read-host "Enter a name to look up their details"
$searchKey = CreateKey $search
if ($hash.ContainsKey($searchKey))
{
}
else
{
write-host "The person you entered does not match any of the people in the dictionary."
}
答案 0 :(得分:2)
尝试这样的事情:
$search = read-host "Enter a name to look up their details"
$searchKey = CreateKey $search
$foundKeys = @()
$foundKeys = $hash.Keys | % { if($_.contains($searchKey)){$_}}
if ($foundKeys)
{
#now keep in mind that you could have duplicate records. This assumes you don't
write-host "Person found:"
write-host $hash[$searchKey]
write-host $hash[$searchKey + "ADD"]
write-host $hash[$searchKey + "CIT"]
write-host $hash[$searchKey + "STA"]
write-host $hash[$searchKey + "ZIP"]
}
else
{
write-host "The person you entered does not match any of the people in the dictionary."
}
答案 1 :(得分:2)
不要避免整个场景,但实际上看起来你会从这里创建自定义对象中获益(小步骤无论如何都需要哈希表)。最大的原因是您的CreateKey
很可能会创建重复项,因此很有可能会覆盖数据。
与原始代码稍作保持,这样您就可以在$results
数组中搜索您要查找的内容。这清除了对复杂密钥系统的需求。
Write-host"该程序将询问用户名称和\ n有关这些人的其他信息!"
$count = 0
$results = @()
while ($count -lt 3){
$props = @{
name = Read-Host "Please enter the name of person $count"
address = Read-Host "Please enter the address of person $count"
city = Read-Host "Please enter the city of person $count"
state = Read-Host "Please enter the state of person $count"
zip = Read-Host "Please enter the zip of person $count"
}
$results += New-Object -TypeName PsObject -Property $props
$count++
}
$results | Where-Object{$_.Name -eq "Jim Bob"}
基于(主要)键盘糖化的输出
zip : 1435
state : ?
name : Jim Bob
address : 20 asdfl
city : kansas city