I came across a question in Technet Forums about how to merge multiple CSV files into one single CSV with additional column added to the output file that indicates the file name from where it imported. You can read full question at http://social.technet.microsoft.com/Forums/en-US/c9470c3e-37a2-48e0-8170-a235fbee2d2e/merging-several-csv-files-in-one-csv-file?forum=winserverpowershell

To address the need, I prepared a quick PS function. Posting it here for my blog readers reference.

CODE:

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"            
            
}            
            

INPUT FILES AND OUTPUT:

File1.CSV:

csvfile1

File2.CSV

csvfile2

Run the below command to merge above two CSVs.

Merge-CSVFiles -CSVFiles C:\temp\file1.csv,C:\temp\file2.csv -OutputFile c:\temp\output.csv

Output CSV will be like this.

outputcsv

Happy learning…