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.

Contact Me With Your Litigation Support Questions:


  • Twitter Long Shadow

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