Table des matières

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.

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:

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.

Catégories : Powershell

0 commentaire

Laisser un commentaire

Emplacement de l’avatar

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.