-
-
Save randomaccess3/8d229090918c44cc4c61001293779979 to your computer and use it in GitHub Desktop.
Merge-CSVFiles: PowerShell Function to Merge a Folder of CSVs and Append a Filename column
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Usage: Merge-CSVFiles | |
| # Usage: Merge-CSVFiles -Path C:\files\to\merge\ -Filter "*.csv" -OutputFile C:\Temp | |
| # 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 = ".\output.csv" | |
| ) | |
| if (!(Test-Path -path $Path)) { | |
| Write-Host "`n`n ERROR: Path ""$Path"" is invalid`n" | |
| break | |
| } | |
| $OutputFile | |
| $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