1

I am trying to compare 2 CSV files i.e. Old.csv and new.csv. I want to compare and print only those lines which are not in old.csv as compared to the new.csv.

I want to print only new files which are not there in old file.

$a = Import-Csv -Path C:\Users\subhatnagar\Desktop\old.csv 
$b = Import-Csv -Path C:\Users\subhatnagar\Desktop\new.csv

$Green = $b | Where {$a -notcontains $_} $green
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Sunny
  • 11
  • 3
  • 1
    What have you tried so far? – Tim Aug 02 '18 at 05:38
  • Please edit your question and don't post code in comments. Thank you – Tim Aug 02 '18 at 05:40
  • They are actually different objects, so it's not comparing if they hold the same values, it's comparing if they are the same things in memory, and they aren't. You will need to use `Compare-Object` and compare all their properties, to do what you want, as in this example: https://stackoverflow.com/a/45270537/478656 - or use `Get-Content` to do it the way you are doing it and compare them "line of text by line of text". `compare-object -ReferenceObject $a -DifferenceObject $b -Property $a[0].psobject.properties.name` – TessellatingHeckler Aug 02 '18 at 05:55

2 Answers2

3

Given that you want to find the new lines between two .csv files, you can use Compare-Object.

$a = Import-Csv -Path C:\Users\subhatnagar\Desktop\old.csv 
$b = Import-Csv -Path C:\Users\subhatnagar\Desktop\new.csv

Compare-Object  -ReferenceObject $a -DifferenceObject $b | Select-Object -ExpandProperty InputObject | Export-Csv C:\Users\subhatnagar\Desktop\difference.csv -NoTypeInformation

Explanation of the Command:

Compare-Object -ReferenceObject $a -DifferenceObject $b - Find the Difference between to Objects

Select-Object -ExpandProperty InputObject - Show only the different Objects and not the Indicator of Compare-Object

Export-Csv -NoTypeInformation - Stores the piped values into a .csv file without Type-Header.


If you only want to store the difference in a variable just delete the Export-Csv part:

$green = Compare-Object  -ReferenceObject $a -DifferenceObject $b | Select-Object -ExpandProperty InputObject
Paxz
  • 2,959
  • 1
  • 20
  • 34
1

If you just interested in "only those lines which are not in old.csv as compared to the new.csv" and not in objects and as objects imported from .csv files contain only string type properties anyways.
Your suggestion in your question might actually work for you, but you will need to get the content as lines (using Get-Content) and not as objects (using Import-Csv)

$a = Get-Content -Path C:\Users\subhatnagar\Desktop\old.csv
$b = Get-Content -Path C:\Users\subhatnagar\Desktop\new.csv

$green = $b | Where {$a -notContains $_}
$green

Beware that this solution compares the lines and not the objects, this means that if e.g. swap a column, all the lines in the new.csv file are considered different which would not be the case if you handle the input as objects.

iRon
  • 20,463
  • 10
  • 53
  • 79