Skip to content

Instantly share code, notes, and snippets.

@svch0stz
Last active August 31, 2020 00:23
Show Gist options
  • Save svch0stz/ab7d93b0872a094e89a09d73dbe6eb3f to your computer and use it in GitHub Desktop.
Save svch0stz/ab7d93b0872a094e89a09d73dbe6eb3f to your computer and use it in GitHub Desktop.
Merge-CSVFiles: PowerShell Function to Merge a Folder of CSVs and Append a Filename column
# Usage: Merge-CSVFiles
# Usage: Merge-CSVFiles -Path C:\files\to\merge\ -Filter "*.csv" -OutputFile C:\Temp\merged.csv
# Combination of https://declanbright.com/downloads/Combine-Files.ps1 and https://gallery.technet.microsoft.com/scriptcenter/CombineMerge-multiple-CSV-23a53e83
function Merge-CSVFiles {
[cmdletbinding()]
param(
[string]$Path = ".",
[string]$Filter = "*.csv",
[string]$OutputFile = "c:\Temp\Merged_$(get-date -f yyyy-MM-dd_HHmmss).csv"
)
if (!(Test-Path -path $Path)) {
Write-Host "`n`n ERROR: Path ""$Path"" is invalid`n"
break
}
$Files = Get-ChildItem $Path -filter $Filter
$Output = @();
foreach($CSV in $Files) {
$fullpath = $Path + $CSV
Write-Host $fullpath
if(Test-Path $fullpath) {
$FileName = [System.IO.Path]::GetFileName($fullpath)
$temp = Import-CSV -Path $fullpath | select *, @{Expression={$FileName};Label="FileName" }
$Output += $temp
} else {
Write-Warning "$fullpath : No such file found"
}
}
$Output | Export-Csv -Path $OutputFile -NoTypeInformation
Write-Output "$OutputFile successfully created"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment