Created
October 15, 2019 18:28
-
-
Save joerodgers/ee2bb713aae77aad7b78f1189a06ae27 to your computer and use it in GitHub Desktop.
Merges one csv into another csv file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Merge-CSV | |
{ | |
[CmdletBinding()] | |
param | |
( | |
[parameter(Mandatory=$true)][string]$PrimaryCSVPath, | |
[parameter(Mandatory=$true)][string]$SecondaryCSVPath, | |
[parameter(Mandatory=$true)][string]$PrimaryCSVKey, | |
[parameter(Mandatory=$true)][string]$SecondaryCSVKey | |
) | |
begin | |
{ | |
} | |
process | |
{ | |
$primaryCSVRows = Import-Csv -Path $PrimaryCSVPath | |
$secondaryCSVRows = Import-Csv -Path $SecondaryCSVPath | |
foreach( $primaryCSVRow in $primaryCSVRows ) | |
{ | |
$secondaryCSVRow = $secondaryCSVRows | ? { $_.$SecondaryCSVKey -eq $primaryCSVRow.$PrimaryCSVKey } | |
$object = New-Object PSObject | |
foreach( $property in $primaryCSVRow.PSObject.properties ) | |
{ | |
$object | Add-Member -MemberType NoteProperty -Name $property.Name -Value $primaryCSVRow.$($property.Name) | |
} | |
foreach( $property in $secondaryCSVRow.psobject.properties ) | |
{ | |
if( -not ($object.psobject.properties | ? Name -eq $property.Name) ) | |
{ | |
$object | Add-Member -MemberType NoteProperty -Name $property.Name -Value $secondaryCSVRow.$($property.Name) | |
} | |
} | |
$object | |
} | |
} | |
end | |
{ | |
} | |
} | |
<# | |
EXAMPLE PRIMARY CSV | |
Login COL1 COL2 COL3 | |
----- ---- ---- ---- | |
joe AA BB CC | |
brian XX DD YY | |
EXAMPLE SECONDARY CSV | |
UserName COL3 COL4 COL5 | |
-------- ---- ---- ---- | |
joe FF AA RR | |
john II HH UU | |
EXAMPLE OUTPUT | |
Login COL1 COL2 COL3 UserName COL4 COL5 | |
----- ---- ---- ---- -------- ---- ---- | |
joe AA BB CC joe AA RR | |
brian XX DD YY | |
#> | |
Merge-CSV -PrimaryCSVPath "C:\_temp\PRIMARY.csv" -SecondaryCSVPath "C:\_temp\SECONDARY.csv" -PrimaryCSVKey "Login" -SecondaryCSVKey "UserName" | FT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment