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

如何在使用Powershell比较两个哈希表时选择特定的哈希表键和值?,powershell,foreach,compare,hashtable,Powershell,Foreach,Compare,Hashtable,我需要比较和合并两个哈希表,但保留特定键的值 $Left = @{Name = "Alex"; CreationDate = "2018-10-20"; Status = "Married"} $Right = @{CreationDate = "2019-03-15"; Status = "Divorced"; City = "NY"; Country = "US"} 一旦这两者合并,名称就不应更改,创建日期必须保持为“2001-10-20”,如$Left表所示,状态需要更新,城市和国家应添

我需要比较和合并两个哈希表,但保留特定键的值

$Left = @{Name = "Alex"; CreationDate = "2018-10-20"; Status = "Married"}
$Right = @{CreationDate = "2019-03-15"; Status = "Divorced"; City = "NY"; Country = "US"}
一旦这两者合并,名称就不应更改,创建日期必须保持为“2001-10-20”,如$Left表所示,状态需要更新,城市和国家应添加到列表中。 下面的脚本正在正确更新、添加和保留所有键的值,但它覆盖了我的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值,但目前为止我无法完成此操作。

这相当简单,但它可以工作。[咧嘴笑]

它的作用

  • 迭代表的新版本中的键
  • 如果键为
    状态
    ,则使用新值更新旧版本
  • 如果该键不在旧版本的键列表中,请添加该键及其值
由于哈希表是通过引用传递的,所以如果需要,可以将其放入函数中。我不确定这样做是否有意义,tho。我可能会把它放在一个循环中来处理你收藏的物品

代码

$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