【问题标题】:Combine two dictionaries and replace keys with values in powershell结合两个字典并用powershell中的值替换键
【发布时间】:2021-10-04 17:14:09
【问题描述】:

我有两个如下所示的数组:

$ht1 = @{

"computer55" = "port33"

“computer1” = “port1”

“computer2” = “port2”



}

$ht2 = @{

"A1:B2:C3:D4:E5:F6" = "port1"

"A2:B3:C4:D5:E6:F7" = "port2"

"A3:B4:C5:D6:E7:F8" = "port33"

"A4:B4:C5:D6:E7:F8" = "port45"
}

第一个是我手动硬编码到脚本中的,我有一个实际的设备名称列表以及它们在交换机上插入的端口。第二个是用switch脚本生成的,登录后获取mac地址表并记录为hashtable。

我想要的结果是这样,如果有一个指定名称的端口,请将端口名称替换为设备名称。

$ht3(or any name) = @{

"A1:B2:C3:D4:E5:F6" = "computer1"

"A2:B3:C4:D5:E6:F7" = "computer2"

"A3:B4:C5:D6:E7:F8" = "computer55"

"A4:B4:C5:D6:E7:F8" = "port45"
}

不知何故,我花了大约一天的时间(...几乎是我想出的第一个 powershell 脚本),我的最终结果总是一样的,我最终合并了两个哈希表并配对端口使用计算机名称,而不是带有计算机名称的 mac 地址。任何方向表示赞赏

【问题讨论】:

    标签: powershell merge hashtable


    【解决方案1】:

    重要提示,.ContainsValue 方法区分大小写,如果您想要不区分大小写的搜索,请使用以下方法之一:

    if($val = [string]$ht1.Keys.Where({$ht1[$_] -eq $ht2[$key]}))
    {
        @{$key = $val}
        continue
    }
    
    if($ht1.Values -contains $ht2[$key])
    {
        ...
    }
    
    if($ht2[$key] -in $ht1.Values)
    {
       ...
    }
    

    代码

    $ht1 = @{
        computer55 = 'port33'
        computer1 = 'port1'
        computer2 = 'port2'
    }
    
    $ht2 = @{
        'A1:B2:C3:D4:E5:F6' = 'port1'
        'A2:B3:C4:D5:E6:F7' = 'port2'
        'A3:B4:C5:D6:E7:F8' = 'port33'
        'A4:B4:C5:D6:E7:F8' = 'port45'
    }
    
    $result = foreach($key in $ht2.Keys)
    {
        if($ht1.ContainsValue($ht2[$key]))
        {
            @{$key = [string]$ht1.Keys.Where({$ht1[$_] -eq $ht2[$key]})}
            continue
        }
        @{$key = $ht2[$key]}
    }
    

    查看$result 产生:

    Name                           Value      
    ----                           -----      
    A1:B2:C3:D4:E5:F6              computer1  
    A3:B4:C5:D6:E7:F8              computer55 
    A4:B4:C5:D6:E7:F8              port45     
    A2:B3:C4:D5:E6:F7              computer2  
    

    [string]$ht1.Keys.Where({$ht1[$_] -eq $ht2[$key]})
    

    也可能是以下,但我不确定哪个更有效:

    $ht1.GetEnumerator().Where({$_.Value -eq $ht2[$key]}).Key
    

    【讨论】:

    • 伙计,对于我花了很长时间的事情来说,这是一个多么简单的解决方案。谢谢。
    • @jsss 乐于助人,这是一个有趣的练习 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 2016-04-14
    • 1970-01-01
    • 2016-06-20
    相关资源
    最近更新 更多