在PowerShell中合并哈希表:如何? [英] Merging hashtables in PowerShell: how?
问题描述
我正在尝试合并两个哈希表,如果第二个中存在相同的键,则覆盖第一个中的键值对.
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.
我在做什么错了?
推荐答案
我看到两个问题:
- 大括号应与
Foreach-object
在同一行
- 在枚举集合时,您不应修改集合
- The open brace should be on the same line as
Foreach-object
- 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屋!