如何在使用 Powershell 比较两个哈希表时 select 特定的哈希表键和值?

How to select a particular hashtable key and value while comparing two hashtables with Powershell?

我需要比较和合并两个散列 table,但保留特定键的值。

$Left = @{Name = "Alex"; CreationDate = "2018-10-20"; Status = "Married"}
$Right = @{CreationDate = "2019-03-15"; Status = "Divorced"; City = "NY"; Country = "US"}

这两个合并后,名称不应更改,创建日期必须保持“2001-10-20”如在 $Left table 中,需要更新 Status,并将 City 和 Country 附加到列表中。 以下脚本会正确更新、添加和保留所有键的值,但它会覆盖我的 CreationDate。

这是为了使用 Powershell 更新一些文件标签。

function New-Result($Key, $Value) {
        New-Object -Type PSObject -Property @{
                    Key    = $Key
                    Value = $Value
            }
    }
    [Object[]]$Results = $Left.Keys | % {
        if ($Left.ContainsKey($_) -and !$Right.ContainsKey($_)) {
            New-Result $_ $Left[$_]
        }
    }
    $Results += $Right.Keys | % {
        if (!$Left.ContainsKey($_) -and $Right.ContainsKey($_) -and ($Right[$_])){
                New-Result $_ $Right[$_]

        }
    }

    $Results += $Right.Keys | % {
        if ($Left.ContainsKey($_) -and $Right.ContainsKey($_) -and ($Right[$_])) {
            New-Result $_ $Right[$_]
        } 
    }
    return $Results 

我需要为 CreationDate 键选择 $Left 值,但目前无法完成。

这很普通,但很管用。 [咧嘴一笑]

它的作用...

  • 遍历 new 版本 table
  • 中的键
  • 如果密钥是 Status,请使用新值
  • 更新 版本
  • 如果键不在版本的键列表中,添加它和它的值

因为 hashtables 是通过引用传递的,如果需要你可以把它放在一个函数中。我不确定这样做是否有意义,不过。我可能会把它放在一个循环中来处理你 collection 中的项目。

代码 ...

$Original = @{
    Name = "Alex"
    CreationDate = "2018-10-20"
    Status = "Married"
    }
$Updated = @{
    CreationDate = "2019-03-15"
    Status = "Divorced"
    City = "NY"
    Country = "US"
    }

foreach ($Key in $Updated.Keys)
    {
    if ($Key -eq 'Status')
        {
        $Original[$Key] = $Updated[$Key]
        }
    if ($Key -notin $Original.Keys)
        {
        $Original.Add($Key, $Updated[$Key])
        }
    }

$Original

输出...

Name                           Value
----                           -----
CreationDate                   2018-10-20
Status                         Divorced
Name                           Alex
City                           NY
Country                        US