I have the need to export data to a CSV, with the requirement of two of the headers having identical names:
date,employee,employee
This is a requirement for a system that the export will then feed into, however I cannot seem to add duplicate headers:
The property cannot be processed because the property "Employee" already exists.
What would be the best way to achieve this?
CodePudding user response:
You'll have to create such a nonstandard CSV file (with duplicate column names) with plain-text processing:
# The nonstandard header.
$customHeader = 'date,employee,employee'
# Get the data rows in memory, using ConvertTo-Csv
# (Uses two sample input objects.)
$null, $dataRows =
[PSCustomObject]@{ date = Get-Date; emp1 = 'jdoe10'; emp2 = 'jroe20' },
[PSCustomObject]@{ date = Get-Date; emp1 = 'jdoe11'; emp2 = 'jroe21' } |
ConvertTo-Csv
# Save the custom header and the data rows to the output file.
# Adjust -Encoding as needed.
$customHeader, $dataRows | Set-Content -Encoding utf8 out.csv
Sample content of the resulting out.csv
file:
date,employee,employee
"9/28/2021 12:33:30 PM","jdoe10","jroe20"
"9/28/2021 12:33:30 PM","jdoe11","jroe21"
CodePudding user response:
Thank you guys for your responses. I've figured out a quicker method, which seems to be doing the job.
I've exported a CSV using date,employee,employee1
And then added the following line to the end of the script, to rename the header...
[io.file]::readalltext($CSV).replace("Employee1","Employee") | Out-File $CSV -Encoding utf8