Compare Two CSVs, match the columns on 2 or more Columns, export specific columns from both csvs with powershell

后端 未结 5 862
傲寒
傲寒 2021-01-24 06:33

i Have 2 CSV\'s

left.csv

Ref_ID,First_Name,Last_Name,DOB
321364060,User1,Micah,11/01/1969
946497594,User2,Acker,05/28/1960
887327716,User3,Aco,06/26/1950         


        
5条回答
  •  Happy的楠姐
    2021-01-24 07:32

    Some good answers already, and here's another.

    Import your myriad objects into a single (dis)array:

    $left = @"
    Ref_ID,First_Name,Last_Name,DOB
    321364060,User1,Micah,11/01/1969
    946497594,User2,Acker,05/28/1960
    887327716,User3,Aco,06/26/1950
    588496260,User4,John,05/23/1960
    565465465,User5,Jack,07/08/2020
    "@
    
    $right = @"
    First_Name,Last_Name,DOB,City,Document_Type,Filename
    User1,Micah,11/01/1969,Parker,Transcript,T4IJZSYO.pdf
    User2,Acker,05/28/1960,,Transcript,R4IKTRYN.pdf
    User3,Aco,06/26/1950,,Transcript,R4IKTHMK.pdf
    User4,John,05/23/1960,,Letter,R4IKTHSL.pdf
    "@
    
    $disarray = @(
        $left | ConvertFrom-Csv 
        $right | ConvertFrom-Csv
    )
    

    Use Group-Object to organize them into groups having identical key values:

    $keyProps = @('First_Name', 'Last_name', 'DOB')
    $disarray | 
        Group-Object -Property $keyProps | 
        Where-Object Count -gt 1 |
    

    Then merge the objects, adding any missing properties to the output $mergedObject

        ForEach-Object {
            $mergedObject = $_.group[0]
            foreach ($obj in $_.group[1..($_.group.count-1)]) {
                $newProps = ($obj | Get-Member -MemberType NoteProperty).name | 
                    Where-Object {
                        $_ -notin ($mergedobject | Get-Member -MemberType NoteProperty).name
                    } 
                foreach ($propName in $newProps) {
                    $mergedObject | Add-Member -MemberType NoteProperty -Name $propName -Value $obj.$propName -Force
                }
            }
            Write-Output $mergedObject
        }
    

    This doesn't differ wildly from the answers you already have, but eliminating the "left" "right" distinction might be helpful; The above code should handle three or more sources thrown into $disarray, merging all objects containing identical $keyProps.

    Note that there are corner cases to consider. For instance, what happens if one object has 'City=Chigago' for a user and another has 'City=New York'?

提交回复
热议问题