Powershell - 将重复的键但不同的值添加到散列中 table

Powershell - add duplicate key but different values into a hash table

如何将具有不同值的重复键添加到散列中 table 以便稍后在 Powershell 的 foreach 循环中使用它?即

$VM = "computer1"

$HashTable = @{ }
$HashTable.Add("key", $VM)

...some script, if statements, ....

$VM = "computer2"
$HashTable.Add("key", $VM)
.....

ForEach ($machine in $HashTable.values)
{
do something for $machine
}

我收到一个错误: "Exception calling "用“2”个参数添加“:"Item has already been added. Key in dictionary: 'key' Key being added: 'key'"

哈希 Table(或字典)中不能有重复键,但您可以这样做:

$HashTable = @{}

$VM = "computer1"
[Array]$HashTable['Key'] += $VM

$VM = "computer2"
[Array]$HashTable['Key'] += $VM

ForEach ($machine in $HashTable['Key'])
{
    Write-Host $Machine
}

但我真的怀疑你是否想这样做。相反,我猜你的 $VM 实际上应该是关键,而不是你能做的:ForEach ($machine in $HashTable.Keys) {...}

我不得不做类似的事情,所以我只是使用 Dict/HT 的数组。非常适合我对重复 Dict/HT 完成的重复键的需求。您的 HT/Dict 中的任何 methods/properties 都将在数组(列表)中可用。 Powershell 非常适合检查列表中的项目。

创建 HT 的列表、HT 的对象或 HT 的对象的无限循环很容易,您的访问和检索方式应该可以帮助您选择所需的内容。

享受吧。 HTH.

# using arraylist classic but works with any .
# then add HT's/Dict's of one item each .
$a = New-Object System.Collections.ArrayList
[Void]$a.Add( @{ "Dict_1" = "Val_1" } ) 
[Void]$a.Add( @{ "Dict_2" = "Val_2" } )
[Void]$a.Add( @{ "Dict_3" = "Val_3" } )
[Void]$a.Add( @{ "Dict_1" = "Val_1001" } )
# then you can use various methods to get items or go through them.
# as you are looking for you can get more than one item back (duplicates) from a search.
# this includes T/F 'containskey()' kind of searches.
# account for those methods and this works like a snap.
ForEach ($HT in $a)
{
   $HT['Dict_1']
}

$a.Keys
$a.Keys -eq 'Dict_1'
$a.GetEnumerator() | Where Keys -eq 'Dict_1'
$a.Values    
$a.ContainsKey('Dict_1') 
$a.ContainsValue('Val_1')