【问题标题】:Powershell. Combine properties of objects in array电源外壳。组合数组中对象的属性
【发布时间】:2020-11-12 22:41:25
【问题描述】:

我不太擅长 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


    【解决方案1】:

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

    此外,您可以使用隐藏的.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
    

    注意:

    • 在您的尝试中,其中一个原始对象已就地修改。

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

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 2021-11-24
      • 2017-11-08
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      相关资源
      最近更新 更多