H
asked on
Create a row of column headers
If a csv doesn't have headers I would like to create a row of column headers depending on the number of columns in a csv.
If for example there are 3 columns I would like three column headers to be in the row
e.g. Column1, Column2, Column3
I am counting the number of columns in a csv using the following script
$Count = (Get-Content $File -First 1).Split($Delimiter).Count .
I'm unsure how to create a row of column names from the count.
Any help would be greatly appreciated
If for example there are 3 columns I would like three column headers to be in the row
e.g. Column1, Column2, Column3
I am counting the number of columns in a csv using the following script
$Count = (Get-Content $File -First 1).Split($Delimiter).Count
I'm unsure how to create a row of column names from the count.
Any help would be greatly appreciated
Be aware that it is possible for delimiter characters to appear in a field. As long as that field is quote delimited, the CSV will parse correctly by applications expecting a well-formed CSV. You can run into problems if you use a Split operation on such files as you will get an incorrect column count.
ASKER
Thank you both for your comments :)
Raheman - I need to store the column names in a variable. e.g. $ColumnNames would equal 'Column1, Column2, Column3' if there are 3 columns. I'm doing further work in the script and the column names need to be stored in a variable to be used for further work in the script. How could I store the column names in a variable please?
Aikimark - Thank for your comment, I will be very mindful of this in the script. :)
Raheman - I need to store the column names in a variable. e.g. $ColumnNames would equal 'Column1, Column2, Column3' if there are 3 columns. I'm doing further work in the script and the column names need to be stored in a variable to be used for further work in the script. How could I store the column names in a variable please?
Aikimark - Thank for your comment, I will be very mindful of this in the script. :)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
oBdA
That's a much cleaner version than what I was thinking of. I won't bother to post my overly complicated version.
And thanks for the link.
That's a much cleaner version than what I was thinking of. I won't bother to post my overly complicated version.
And thanks for the link.
ASKER
oBdA thank you for the solution, it works really well. :)
ASKER
Thank you all very much for your help. It is much appreciated. :)
try this:
$file = "D:\temp2\input.csv"
$output = "D:\temp2\output.csv"
if (Test-Path $output)
{
del $output
}
$Delimiter = ','
$Count = $((Get-Content $File -First 1).Split($Delimiter)).count
1..$count | % {
"Column$($_)" | add-content $output -NoNewline
if ($_ -ne $count)
{
"," | Add-Content $output -NoNewline
}
}
'' | add-content $output
Get-Content $File | add-content $output