powershell 联接两个对象-无法添加名为“x”的成员,因为具有该名称的成员已存在?

eqqqjvef  于 2022-11-29  发布在  Shell
关注(0)|答案(1)|浏览(167)

以下代码将datadata2连接起来,并创建一个非规范化的CSV文件。

$str = '{
    "data": [
        { "attrs": { "id": "A", "more": "A" }, 
          "relations": [{"id": "r11"}, {"id": "r12"}] },
        { "attrs": { "id": "B", "more": "B" }, 
          "relations": [{"id": "r21"}] }
    ],
    "data2": [
        {"id": "r11", "attrs": { "x": "11", "y": "1"}},
        {"id": "r12", "attrs": { "x": "12", "y": "2"}},
        {"id": "r21", "attrs": { "x": "21", "y": "1"}}
    ]}'
$json = $str | ConvertFrom-Json

$json.data | 
% {
    #$data = $null
    $data = $_.attrs
    $_.relations.id | #select -first 1 | 
    % {
        $d2 = $json.data2 | ? id -eq $_ | select -ExpandProperty attrs
        Write-Host -ForegroundColor Green $d2
        $d2 | Get-Member -Type Properties | % {
            Write-Host -ForegroundColor Red $_
            Add-Member -InputObject $data -NotePropertyName $_.Name -NotePropertyValue $_
        }
        $data
    } 
} | 
ConvertTo-Csv

但是,它得到了以下错误?

Add-Member: 
Line |
  12 |              Add-Member -InputObject $data -NotePropertyName $_.Name - …
     |              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot add a member with the name "x" because a member with that name already exists. To overwrite the member anyway, add the Force parameter to your command.
string y=1
6g8kf2rb

6g8kf2rb1#

因为data中的每个attrs都可能有多个relation.id,所以您将attrsAdd-Member)两次添加到d2对象,因此您需要首先解开data对象(请参阅我对您之前问题的回答:Zip two select list?以创建平面$data$data2对象)。
正如在In PowerShell, what's the best way to join two tables into one?的一些答案中所解释的,使用哈希表可能是最简单和最快的:

$Hashtable = @{}
$Data2.ForEach{ $Hashtable[$_.id] = $_}

$Hashtable

Name                           Value
----                           -----
r12                            @{id=r12; x=12; y=2}
r21                            @{id=r21; x=21; y=1}
r11                            @{id=r11; x=11; y=1}

然后将属性添加到$data对象:

$data.ForEach{
     $_ |Add-Member -NotePropertyName x -NotePropertyValue $HashTable[$_.relation].x
     $_ |Add-Member -NotePropertyName y -NotePropertyValue $HashTable[$_.relation].y
}

$data |Format-Table

relation id more x  y
-------- -- ---- -  -
r11      A  A    11 1
r12      A  A    12 2
r21      B  B    21 1

如果您不想重新发明轮子,您还可以使用Join-Object script/Join-Object Modulemy answer

$data |Join $data2 -on relation -eq id |Format-Table

relation id more x  y
-------- -- ---- -  -
r11      A  A    11 1
r12      A  A    12 2
r21      B  B    21 1

相关问题