top of page

PowerShell script to merge .csv files


A PowerShell script posted on the Microsoft Scripting blog here, can be used to merge multiple .csv files together.

Begin by entering this source code for the merge function in PowerShell:

function Merge-CSVFiles { [cmdletbinding()] param( [string[]]$CSVFiles, [string]$OutputFile = "c:\merged.csv" ) $Output = @(); foreach($CSV in $CSVFiles) { if(Test-Path $CSV) { $FileName = [System.IO.Path]::GetFileName($CSV) $temp = Import-CSV -Path $CSV | select *, @{Expression={$FileName};Label="FileName"} $Output += $temp } else { Write-Warning "$CSV : No such file found" } } $Output | Export-Csv -Path $OutputFile -NoTypeInformation Write-Output "$OutputFile successfully created" }

Enter this code and press return. The function will be activated. Next compose a simple line of script which references the full path for each of the .csv files you want to merge together:

Merge-CSVFiles -CSVFiles C:\foofolder8\AllstarFull.csv,C:\foofolder8\Appearances.csv,C:\foofolder8\Batting.csv -OutputFile c:\foofolder8\output.csv

Separate the listed .csv files with a comma. At the end of the script, enter a path for the resulting file which will contain the merged data.

The new .csv file will contain a new column at the right which lists the name of each source file.

As always, I tested out this script myself tonight, and confirmed that it functions correctly.


Sean O'Shea has more than 20 years of experience in the litigation support field with major law firms in New York and San Francisco.   He is an ACEDS Certified eDiscovery Specialist and a Relativity Certified Administrator.

​

The views expressed in this blog are those of the owner and do not reflect the views or opinions of the owner’s employer.

​

If you have a question or comment about this blog, please make a submission using the form to the right. 

Your details were sent successfully!

© 2015 by Sean O'Shea . Proudly created with Wix.com

bottom of page