Compare two csv-files and remove the same values

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 3 years, 7 months ago.

  • Author
    Posts
  • #11369
    Profile photo of Dominique Hofmann
    Dominique Hofmann
    Participant

    Hello Together
    I have two csv-files Path.csv and Report.csv and i want to compare the different paths, which are saved in both csv-files.
    And after it compared the csv-files i want to remove the same paths in each csv-file.
    I tried it with Select-object and where-object but it didn't worked.
    If somebody have an idea write me thanks

  • #11376
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    There may be more efficient ways of doing this, but I'd use a combination of Compare-Object and the -notin or -notcontains operators, like this:

    $csvPath1 = '.\test.csv'
    $csvPath2 = '.\test2.csv'
    
    $propertyToCompare = 'Path'
    
    $csv1 = Import-Csv -Path $csvPath1
    $csv2 = Import-Csv -Path $csvPath2
    
    $duplicates = Compare-Object $csv1 $csv2 -Property $propertyToCompare -IncludeEqual -ExcludeDifferent -PassThru |
    Select-Object -ExpandProperty $propertyToCompare
    
    $csv1 |
    Where-Object { $_.$propertyToCompare -notin $duplicates } |
    Export-Csv -Path $csvPath1 -NoTypeInformation
    
    $csv2 |
    Where-Object { $_.$propertyToCompare -notin $duplicates } |
    Export-Csv -Path $csvPath2 -NoTypeInformation
    

You must be logged in to reply to this topic.