0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PowerShellでCSVを取り込んでLeft Joinしたい

Posted at

絶対昔書いてると思ったけど見つからなかった

Join-Table.ps1
function Join-Record {
    param($record1, $record2)
    $o = New-Object psobject

    $record1 | gm -MemberType NoteProperty | % {
        $name = $_.name
        $o | Add-Member NoteProperty -Name "$name" -Value $record1.$name
    }

    $record2 | gm -MemberType NoteProperty | % {
        $name = $_.name
        if ($o.psobject.properties.Name -contains $name) {
            $o | Add-Member NoteProperty -Name "Right.$name" -Value $record2.$name
        } else {
            $o | Add-Member NoteProperty -Name "$name" -Value $record2.$name
        }
    }
    return $o
}

function Join-Table {
    param(
        $From,
        $LeftJoin,
        $On,
        $Equal
    )

    $From | % {
        $FromRecord = $_
        $i = 0
        $LeftJoin | % {
            $LeftJoinRecord = $_
            if ($FromRecord.$On -eq $LeftJoinRecord.$Equal){
                Join-Record $FromRecord $LeftJoinRecord
                $i += 1
            }
        }
        if ($i -eq 0) {
            $PseudoLeftJoinRecord = New-Object psobject
            $LeftJoin | select-object -first 1 | % { $_.psobject.properties } | % {
                $PseudoLeftJoinRecord | Add-Member NoteProperty -Name $_.Name -Value ""
            }
            Join-Record $FromRecord $PseudoLeftJoinRecord
        }
    }
}

sample.ps1
. Join-Table.ps1

$a = 1..10 | % {
    [pscustomobject]@{
        Id = $_
        A = "A"
    }
}

$b = 1,2,3,4 | % {
    [pscustomobject]@{
        Id = $_
        B = "B"
    }
}

Join-Table -From $a -LeftJoin $b -On Id -Equal Id | ft -auto
A Id B Right.Id
- -- - --------
A  1 B        1
A  2 B        2
A  3 B        3
A  4 B        4
A  5           
A  6           
A  7           
A  8           
A  9           
A 10           

レコード数増えたら遅くなりそう。Excel に入れたい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?