'Comparing and extracting data from CSV file using powershell

I have a csv1 file with data:

enter image description here

I have a csv2 file with data:

enter image description here

Now I want to extract data from csv2 file which has data in common with csv1 file. For example csv1 first line [email protected] and sales should compare with lines in csv2 if the line matches I have to get the data from csv2 file like [email protected],sales,chennai and [email protected],Marketing,Bangalore. Hope you understood my question. Please help me to write a powershell script for this one.



Solution 1:[1]

Given the identical column names, you can use Compare-Object to extract the rows from the second CSV where a matching row exists in the first CSV:

$csv1 = Import-Csv path\to\first_file.csv
$csv2 = Import-Csv path\to\second_file.csv

Compare-Object $csv2 $csv1 -Property EmailID,Department -IncludeEqual -ExcludeDifferent -PassThru |Select-Object * -ExcludeProperty SideIndicator
  • -Property EmailID,Department ensures that Compare-Object compares both of those properties on all input objects.
  • -IncludeEqual, -ExcludeDifferent ensure we get the rows from CSV 2 that matches some row from CSV 1 rather than those that are different.
  • -PassThru gives us the original input objects from $csv2
  • Piping to Select-Object * -ExcludeProperty SideIndicator removes the SideIndicator property attached by Compare-Object

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mathias R. Jessen