powershell - 结合两个字典并用powershell中的值替换键
问题描述
我有两个看起来像这样的数组:
$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"
}
第一个是我手动硬编码到脚本中的一个,我有一个实际的设备名称列表以及它们在交换机上插入的端口。第二个是使用登录的切换脚本生成的,获取mac地址表并将其记录为哈希表。
我想要的结果是,如果有一个指定名称的端口,请将端口名称替换为设备名称。
$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 地址。任何方向表示赞赏
解决方案
重要说明,该.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
推荐阅读
- c++ - C++链表反向遍历内存损坏
- java - 为 Java 设置 Selenium(创建 Firefox 驱动程序所需的 jar 和导入)
- php - 在自定义模板(访问者的课程页面)上打印课程中的课程列表 learndash get_course_lessons()
- python - CSV 列作为单个列表而不是分隔字符串
- scala - 将 RDD[String] 转换为 RDD[myclass]
- python - 石头剪刀布循环问题 Python
- python - 如何修复我的 if 语句不基于随机数生成器重复
- javascript - 在 PHP 网站中添加嵌入式 Youtube 视频会导致控制台出错
- python - 如何防止我的 reddit 机器人评论它已经评论过的帖子?
- amazon-web-services - AWS Cognito 身份池的 Web 界面未保存对经过身份验证的提供者角色选择的更改