DarKZoNe
DarKZoNe

Reputation: 47

How to merge two csv files with PowerShell

I have two .CSV files that contain information about the employees from where I work. The first file (ActiveEmploye.csv) has approximately 70 different fields with 2500 entries. The other one (EmployeEmail.csv) has four fields (FirstName, LastName, Email, FullName) and 700 entries. Both files have the FullName field in common and it is the only thing I can use to compare each file. What I need to do is to add the Email address (from EmployeEmail.csv) to the corresponding employees in ActiveEmploye.csv. And, for those who don't have email address, the field can be left blank.

I tried to use a Join-Object function I found on internet few days ago but the first csv files contain way too much fields for the function can handle.

Any suggestions is highly appreciated!

Upvotes: 3

Views: 10408

Answers (2)

Dan
Dan

Reputation: 732

Here is an alternate method to @BartekB which I used to join multiple fields to the left and had better results for processing time.

Import-Csv EmployeeEmail.csv | ForEach-Object -Begin {
    $Employees = @{}
} -Process {
    $Employees.Add($_.FullName,$_)
}

Import-Csv ActiveEmployees.csv |
    Select *,@{Name="email";Expression={$Employees."$($_.FullName)"."email"}} |
        Export-Csv Joined.csv -NoTypeInformation

This allows one to query the array index of FullName on $Employees and then get the value of a named member on that element.

Upvotes: 0

BartekB
BartekB

Reputation: 8650

There are probably several ways to skin this cat. I would try this one:

Import-Csv EmployeeEmail.csv | ForEach-Object -Begin {
    $Employees = @{}
} -Process {
    $Employees.Add($_.FullName,$_.email)
}

Import-Csv ActiveEmployees.csv | ForEach-Object {
    $_ | Add-Member -MemberType NoteProperty -Name email -Value $Employees."$($_.FullName)" -PassThru
} | Export-Csv -NoTypeInformation Joined.csv

Upvotes: 5

Related Questions