将哈希表添加到哈希表

时间:2018-06-05 17:42:14

标签: powershell hashtable

我正在尝试使用powershell将哈希表添加到哈希表中。但是,我得到以下错误:

Item has already been added. Key in dictionary: 'Dev' Key being added: 'Dev'

这是我的代码:

$colors = @("black","white","yellow","blue")

$Applications=@{}

Foreach ($i in $colors)
{
    $Applications += @{
        Colour = $i
        Prod = 'SrvProd05'
        QA   = 'SrvQA02'
        Dev  = 'SrvDev12'
    }
}

我做错了什么?

2 个答案:

答案 0 :(得分:3)

我认为你想要的更像是这样:

$colors = @("black","white","yellow","blue")
$Applications=@{}
Foreach ($i in $colors)
{
    $Applications[$i] = @{
        Colour = $i
        Prod = 'SrvProd05'
        QA   = 'SrvQA02'
        Dev  = 'SrvDev12'
    }
}

我还要指出,Hashtables经常需要在防御上处理。每个键必须是唯一的,但不需要值。以下是处理该方法的典型方法:

$colors = @("black","white","yellow","blue")
$Applications=@{}
Foreach ($i in $colors)
{
    if($Applications.ContainsKey($i)){
        #Do things here if there is already an entry for this key
    }else{
        $Applications[$i] = @{
            Colour = $i
            Prod = 'SrvProd05'
            QA   = 'SrvQA02'
            Dev  = 'SrvDev12'
        }
    }
}

答案 1 :(得分:0)

EBGreen's helpful answer意味着做的事情提供了解决方案。

为了补充这一点,解释为什么代码失败:

  • 当您使用+来"添加"两个哈希表,它们的条目是合并 :换句话说:RHS的条目被添加到LHS哈希表中。
    (从技术上讲,使用合并的条目创建新实例。)

  • 但是 - 通过合理的设计 - 只有当哈希表没有没有共同的键 时才会执行合并。否则,您将收到您看到的错误消息,抱怨重复的密钥 如果没有这种安全措施,如果与重复条目相关的值不同,您将丢失数据。

由于您的循环重复尝试将具有相同键的哈希表直接合并到现有哈希表中,因此第二次循环迭代总是失败。

您可以更简单地验证这一点:

$Applications = @{}  # create empty hashtable.

# Merge a hashtable literal into $Applications.
# This works fine, because the two hashtables have no keys in common.
$Applications += @{ first = 1; second = 2 } 

# $Application now contains the following: @{ first = 1; second = 2 }

# If you now try to add a hashtable with the same set of keys again,
# the operation invariably fails due to duplicate keys.
$Applications += @{ first = 10; second = 20 } # FAILS

# By contrast, adding a hashtable with unique keys works fine:
$Applications += @{ third = 3; fourth = 4 } # OK

# $Application now contains: @{ first = 1; second = 2; third = 3; fourth = 4 }