在PowerShell中合并哈希表:如何? [英] Merging hashtables in PowerShell: how?

查看:80
本文介绍了在PowerShell中合并哈希表:如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并两个哈希表,如果第二个中存在相同的键,则覆盖第一个中的键值对.

I am trying to merge two hashtables, overwriting key-value pairs in the first if the same key exists in the second.

为此,我编写了此函数,如果第二个哈希表中存在相同的键,则该函数首先删除第一个hastable中的所有键值对.

To do this I wrote this function which first removes all key-value pairs in the first hastable if the same key exists in the second hashtable.

当我逐行将其键入PowerShell时,它可以工作.但是当我运行整个功能时,PowerShell要求我为foreach-object提供(它认为)缺少的参数.

When I type this into PowerShell line by line it works. But when I run the entire function, PowerShell asks me to provide (what it considers) missing parameters to foreach-object.

function mergehashtables($htold, $htnew)
{
    $htold.getenumerator() | foreach-object
    {
        $key = $_.key
        if ($htnew.containskey($key))
        {
            $htold.remove($key)
        }
    }
    $htnew = $htold + $htnew
    return $htnew
}

输出:

PS C:\> mergehashtables $ht $ht2

cmdlet ForEach-Object at command pipeline position 1
Supply values for the following parameters:
Process[0]:

$ ht和$ ht2是哈希表,每个哈希表包含两个键值对,其中两个在两个哈希表中都具有键"name".

$ht and $ht2 are hashtables containing two key-value pairs each, one of them with the key "name" in both hashtables.

我在做什么错了?

推荐答案

我看到两个问题:

  1. 大括号应与Foreach-object
  2. 在同一行
  3. 在枚举集合时,您不应修改集合
  1. The open brace should be on the same line as Foreach-object
  2. You shouldn't modify a collection while enumerating through a collection

下面的示例说明了如何解决这两个问题:

The example below illustrates how to fix both issues:

function mergehashtables($htold, $htnew)
{
    $keys = $htold.getenumerator() | foreach-object {$_.key}
    $keys | foreach-object {
        $key = $_
        if ($htnew.containskey($key))
        {
            $htold.remove($key)
        }
    }
    $htnew = $htold + $htnew
    return $htnew
}

这篇关于在PowerShell中合并哈希表:如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆