Keeping in mind that CSV files may have comment lines preceding the header row, this code gets enough of the CSV file (15 lines) to include the header row and then converts the data to PSCustomObjects (which ignores the comment lines). The first (or any, really) object is then used to extract the column names which are then quoted and joined with commas.
$infile = 'C:\junk\x2.csv'
$outfile = 'C:\junk\x2-1.csv'
$hdr = @()
# Get enough of the CSV to include the header if there are leading
# comment lines in the file
$x = Get-Content $infile -First 15 | ConvertFrom-CSV
$x[0].psobject.Members | # get the property names from the 1st item (ignore the rest)
ForEach-Object{
if ($_.MemberType -eq 'NoteProperty'){
$hdr += '"' + $_.Name + '"' # surround the names with quotes (just in case!)
}
}
$hdr -join ',' | Out-File $outfile # join names with commas and write the header
Here's an example of a commented CSV:
# a comment line
# another comment line
"User","Address","Another piece of data"
"User1","Street1 City1",A
"User2","Street2 City2",B
"User3","Street3 City3",C