Home > Enterprise >  Windows Powershell: How to compare two CSV files and output the rows that are just in either of the
Windows Powershell: How to compare two CSV files and output the rows that are just in either of the

Time:04-22

I have a file first.csv

name,surname,height,city,county,state,zipCode
John,Doe,120,jefferson,Riverside,NJ,8075
Jack,Yan,220,Phila,Riverside,PA,9119
Jill,Fan,120,jefferson,Riverside,NJ,8075
Steve,Tan,220,Phila,Riverside,PA,9119
Alpha,Fan,120,jefferson,Riverside,NJ,8075

and second.csv

name,surname,height,city,county,state,zipCode
John,Doe,120,jefferson,Riverside,NJ,8075
Jack,Yan,220,Phila,Riverside,PA,9119
Jill,Fan,120,jefferson,Riverside,NJ,8075
Steve,Tan,220,Phila,Riverside,PA,9119
Bravo,Tan,220,Phila,Riverside,PA,9119

I want to compare the rows of both first.csv and second.csv files and output the rows that are either in first.csv or second.csv but not in both.

So the output.csv should have

Alpha,Fan,120,jefferson,Riverside,NJ,8075
Bravo,Tan,220,Phila,Riverside,PA,9119

There are quite a few similar questions but the output is not exactly what I want.

Thank you

CodePudding user response:

$filea = Import-Csv C:\Powershell\TestCSVs\group1.csv
$fileb = Import-Csv C:\Powershell\TestCSVs\group2.csv

Compare-Object $filea $fileb -Property name, surname, height, city, county, state, zipCode | Select-Object name, surname, height, city, county, state, zipCode | export-csv C:\Powershell\TestCSVs\out.csv -NoTypeInformation

I'm using the all the fields to compare and sort here but you can specify the unique value(s) that you're wanting to use to match the rows.

output

"name","surname","height","city","county","state","zipCode"     
"Bravo","Tan","220","Phila","Riverside","PA","9119"             
"Alpha","Fan","120","jefferson","Riverside","NJ","8075"
  • Related