【问题标题】:Powershell - add duplicate key but different values into a hash tablePowershell - 将重复的键但不同的值添加到哈希表中
【发布时间】:2020-05-31 01:04:52
【问题描述】:

如何将具有不同值的重复键添加到哈希表中,以便稍后在 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
}

我收到一个错误: “使用“2”个参数调用“添加”的异常:“项目已添加。字典中的键:'key' 正在添加的键:'key'"

【问题讨论】:

    标签: powershell hashtable


    【解决方案1】:

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

    $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) {...}

    【讨论】:

    • 你是对的。无论如何,我想出了使用简单数组: $VM = "computer1" $Array= @{ } $Array +=$VM ...some script, if statements, .... $VM = "computer2" $Array + =$VM ..... ForEach ($machine in $Array) { 为 $machine 做点什么}
    • 既然这为您提供了解决问题的指针,也许标记为答案?
    【解决方案2】:

    我不得不做类似的事情,所以我只使用一个字典/HT 的数组。非常适合我对作为重复 Dict/HT 的重复键的需求。您的 HT/Dict 的任何方法/属性都将在数组(列表)中使用。 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      相关资源
      最近更新 更多