Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell-将重复的键但不同的值添加到哈希表中_Powershell_Hashtable - Fatal编程技术网

Powershell-将重复的键但不同的值添加到哈希表中

Powershell-将重复的键但不同的值添加到哈希表中,powershell,hashtable,Powershell,Hashtable,如何将具有不同值的重复键添加到哈希表中,以便稍后在Powershell中的foreach循环中使用?i、 e $VM = "computer1" $HashTable = @{ } $HashTable.Add("key", $VM) ...some script, if statements, .... $VM = "computer2" $HashTable.Add("key", $VM) ..... ForEach ($machine in $HashTable.values) {

如何将具有不同值的重复键添加到哈希表中,以便稍后在Powershell中的foreach循环中使用?i、 e

$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
}
我得到一个错误:
使用“2”参数调用“Add”时出现异常:“已添加项。”。字典中的键:“键”正在添加的键:“键”

哈希表(或字典)中不能有重复的键,但可以执行以下操作:

$HashTable = @{}

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

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

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

但是我真的怀疑你是否想这样做。相反,我猜你的
$VM
应该是键,而你可以这样做:
ForEach($HashTable.Keys中的机器){…}

你是对的。无论如何,我想到了使用简单数组:$VM=“computer1”$array=@{}$Array+=$VM…一些脚本,if语句,.$VM=“computer2”$Array+=$VM…..ForEach($Array中的机器){为$machine做点什么}因为这为您提供了一个解决问题的指针,也许标记为答案?