Reputation: 1
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:
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!
Upvotes: 0
Views: 877
Reputation: 25001
$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.
Upvotes: 1