Function
Instead of scripting a one-off solution, we’ll craft a reusable function. This approach ensures that you can call upon this method whenever you need to merge CSV files in the future.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | function Merge-CSVFiles { param ( [string] $file1 , [string] $file2 , [string] $output_file = "merged_file.csv" ) # Initialize empty arrays for the CSV data $csv1 = @() $csv2 = @() # Check if file1 exists and read it if ( Test-Path $file1 ) { $csv1 = Import-Csv -Path $file1 -Delimiter ';' } else { Write-Output "Warning: $file1 does not exist." } # Check if file2 exists and read it if ( Test-Path $file2 ) { $csv2 = Import-Csv -Path $file2 -Delimiter ';' } else { Write-Output "Warning: $file2 does not exist." } # Merge the CSV files $merged_csv = $csv1 + $csv2 # Save the merged data to a new CSV file using semicolon as delimiter $merged_csv | Export-Csv -Path $output_file -NoTypeInformation -Delimiter ';' Write-Output "Files have been successfully merged!" } |
Example
With the function in place, you can now call upon it to merge your CSV files. Here’s how:
1 | Merge-CSVFiles -file1 "path_to_your_first_file.csv" -file2 "path_to_your_second_file.csv" -output_file "output.csv" |
Replace path_to_your_first_file.csv
and path_to_your_second_file.csv
with the paths to your CSV files. If you wish to specify a different output filename, use the -output_file
parameter.
0 Comments