0

CSV File 1 (Headers File):

Heading 1, Heading 2, Heading 3 ...

CSV File 2 (Data File):

Data Record 1, Data Record 2, Data Record 3 ...


File 1 contains the headers only, whereas File 2 contains the data which corresponds to the headers in File 1. Is it possible to append the data in File 2, to the Headers in File 1 via a PowerShell script, so File 2 (or a new file) will now look like:

Output CSV File

Heading 1, Heading 2, Heading 3 ...

Data Record 1, Data Record 2, Data Record 3 ...


Appologies for the question formatting, first post here. Would you very grateful for any help, thank you in advance!

2
  • 1
    What have you tried so far? Show us your code and we will be happy to help but we won't write you anything from scratch. Commented Mar 7, 2019 at 15:16
  • the Import-CSV cmdlet has a -Header parameter. you could read the 1st file in with Get-Content and use that as the value for the header parameter when you use Import-CSV on the 2nd file. Commented Mar 7, 2019 at 15:30

1 Answer 1

1
$Headers = (Get-Content csv1.csv).Split(',')
$outputCSV = Import-CSV csv2.csv -Header $Headers
$outputCSV | Export-CSV output.csv -NoTypeInformation

The $Headers variable is storing the comma delimited values from the csv1.csv file (the file that contains only headers).

The Split() method is splitting the contents of csv1.csv at each comma, removing the comma, and creating an array of those splits.

Trim() can be added after the Split() method for removing extra white space around the commas.

$outputCSV is importing csv2.csv as a csv file and adding the header row from the $Headers array.

The final command is exporting the contents of $outputCSV into a new csv file called output.csv.

In the Import-CSV and Export-CSV commands, the file names I've provided are assigned to the -Path parameter. You can fully qualify those paths if necessary, i.e. they do not have to have just the file names only.

Sign up to request clarification or add additional context in comments.

2 Comments

This worked like a charm!! I just had to remove Trim() as CSV File 2 contains quite a few blanks spaces in the data (unfortunately its produced 3rd party). Once I removed Trim() - it merged the data perfectly.
Thanks for the update. I removed the Trim() method from the answer and just kept it as a note.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.