'Comparing and extracting data from CSV file using powershell
I have a csv1 file with data:
I have a csv2 file with data:
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,Departmentensures thatCompare-Objectcompares both of those properties on all input objects.-IncludeEqual,-ExcludeDifferentensure we get the rows from CSV 2 that matches some row from CSV 1 rather than those that are different.-PassThrugives us the original input objects from$csv2- Piping to
Select-Object * -ExcludeProperty SideIndicatorremoves theSideIndicatorproperty attached byCompare-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 |


