问题描述
这是我使用哈希表数组的代码
$podnumbers = @(1,3,1)
$podInfo = $null
$buffer = 0
$podarray = foreach ($pd in $podnumbers) {
$podinfo = @()
for($i=0;$i -lt $pd;$i = $i+1) {
$pod = Read-Host -Prompt "Assign the pod numbers for",$esxarray[$buffer]
Write-Output `n
}
@{$pd = $pod}
$buffer = $buffer + 1
}
我为$ pod提供的输入是1 = 1; 3 = 2,4,6; 1 = 3
我希望我的哈希表数组如下所示,
Key : 1
Value : 1
Name : 1
Key : 3
Value : 2,6
Name : 3
Key : 1
Value : 3
Name : 1
但是我得到的实际输出是
Key : 1
Value : 1
Name : 1
Key : 3
Value : 2
Name : 3
Key : 3
Value : 4
Name : 3
Key : 3
Value : 6
Name : 3
Key : 1
Value : 3
Name : 1
解决方法
如果要向同一个键添加多个值,则需要测试该键是否已经存在并采取相应措施:
$keys = 1,2,3,1
$value = 'a value'
$hashtable = @{}
foreach($key in $keys){
if(-not $hashtable.ContainsKey($key)){
# First time we see this key,let's make sure the value is a resizable array
$hashtable[$key] = @()
}
# Now we can safely add values regardless of whether the key already exists
$hashtable[$key] += $value
}
,
为补充@Matthias中的答案:
hash table中不能有重复的键。这是设计使然。哈希表包含一个基于binary search algorithm的唯一键的列表,其中每个键都链接到特定的对象(值)。
有两个解决方法:
1。将值数组添加到特定的哈希表键:
$Keys = 1,3
$Values = 'a'..'d'
$HashTable = @{}
$i = 0
foreach($key in $Keys){ [array]$HashTable[$Key] += $Values[$i++] }
迭代
缺点是您会丢失项目的顺序(无论您是否仅由于某些值共享单个键而使用ordered字典)。
Foreach ($Key in $Hashtable.Keys) {
Foreach ($Value in @($Hashtable[$Key])) {
Write-Host $Key '=' $Value
}
}
3 = d
2 = b
2 = c
1 = a
搜索
优点是,这些项目已进行了二进制索引,因此可以快速找到。
$SearchKey = 2
Foreach ($Value in @($Hashtable[$SearchKey])) {
Write-Host $SearchKey '=' $Value
}
2 = b
2 = c
2。或者您可以创建哈希表(Key Value Pairs)的列表(数组)
$Keys = 1,3
$Values = 'a'..'d'
$i = 0
$KeyValuePairs = foreach($key in $keys){ @{ $Key = $Values[$i++] } }
迭代
优点是物品会保持秩序。
(请注意,您必须调用GetEnumerator()
方法两次)
$KeyValuePairs.GetEnumerator().GetEnumerator() | Foreach-Object {
Write-Host $_.Key '=' $_.Value
}
1 = a
2 = b
2 = c
3 = d
搜索
缺点是搜索项目的速度较慢,而搜索的范围较广。
$SearchKey = 2
$KeyValuePairs.GetEnumerator().GetEnumerator() |
Where-Object Key -eq $SearchKey | Foreach-Object {
Write-Host $_.Key '=' $_.Value
}
2 = b
2 = c
,
由于您重新定义的新目标比最初出现的问题更具体,因此我在另一个答案中进行此操作。相反,应将每个响应分配给一个相关的podnumber。
脚本:
$podnumbers = @(1,1)
$Inputs = 1,4,6,3
$c = 0
$podarray = foreach ($pd in $podnumbers) {
$podinfo = @{}
for($i=0; $i -lt $pd; $i = $i+1) {
# $pod = Read-Host -Prompt "Assign the pod numbers for",$esxarray[$buffer]
[array]$podinfo[$pd] += $Inputs[$c++]
}
$podinfo
}
$podarray
输出:
Name Value
---- -----
1 {1}
3 {2,6}
1 {3}