首页 > 解决方案 > 电源外壳。组合数组中对象的属性

问题描述

我不太擅长powershell,我需要帮助。我正在尝试组合对象的属性。对于两个对象,一切都很好。这看起来像。

$obj1 = [PSCustomObject]@{
    'ip' = '10.10.10.11'
    't1' = 'show'
    't2' = 'ab'

}
$obj2 = [PSCustomObject]@{
    'ip' = '10.10.10.11'
    't1' = 'me'
    't2' = 'cd'
} 

foreach ($prop in $obj2 | Get-Member -MemberType NoteProperty | Where-Object {$_.name -ne 'ip'} | select -ExpandProperty name)
{
    $obj1.$prop += $obj2.$prop
}

$obj1 

Result:
ip                         t1                         t2                       
--                         --                         --                       
10.10.10.11                showme                     abcd  

但是如果数组中有很多对象,我就不能这样做。怎么做?示例数组:

Array1:
ip                         t1                         t2                       
--                         --                         --                       
10.10.10.11                show                       ab                       
10.10.10.12                show                       ab   

Array2:
ip                         t1                         t2                       
--                         --                         --                       
10.10.10.11                me                         cd                       
10.10.10.12                me                         cd  

标签: powershell

解决方案


基本上,您只需要添加一个遍历数组元素的外循环。

此外,您可以使用隐藏.psobject.Properties成员来简化您的解决方案:

# Sample arrays
$array1 = [pscustomobject]@{ 'ip' = '10.10.10.11'; 't1' = 'show1'; 't2' = 'ab1' },
          [pscustomobject]@{ 'ip' = '10.10.10.12'; 't1' = 'show2'; 't2' = 'ab2' }

$array2 = [pscustomobject]@{ 'ip' = '10.10.10.11'; 't1' = 'me1'; 't2' = 'cd1' },
          [pscustomobject]@{ 'ip' = '10.10.10.12'; 't1' = 'me2'; 't2' = 'cd2' }

# Assuming all objects in the arrays have the same property structure,
# get the list of property names up front.
$mergeProperties = $array1[0].psobject.Properties.Name -ne 'ip'

# Loop over the array elements in pairs and merge their property values.
$i = 0
[array] $mergedArray = 
  foreach ($o1 in $array1) {
    $o2 = $array2[$i++]
    foreach ($p in $mergeProperties) {
        $o1.$p += $o2.$p
    }
    $o1  # output the merged object
  }

输出$mergedArray然后产生:

ip          t1       t2
--          --       --
10.10.10.11 show1me1 ab1cd1
10.10.10.12 show2me2 ab2cd2

笔记:

  • 与您的尝试一样,原始对象之一已就地修改。

  • 假设是两个数组中的匹配对象分别位于相同的位置(将第一个数组中的第一个对象与第二个数组中的第一个对象合并,......)。


推荐阅读