Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Reply To: Replacing csv header row

$
0
0

Sure. There are a couple of ways to go about that; I prefer to import the old CSV file, then use Select-Object to change the property names of objects in memory, and export back to CSV with the new property names (which become the header row). Something like this:

$propertyTranslation = @(
    @{ Name = 'givenName'; Expression = { $_.'First Name' } }
    @{ Name = 'surName';   Expression = { $_.'Last Name'  } }
    # And so on
)
 
(Import-Csv -Path 'yourCsvFile.csv') |
Select-Object -Property $propertyTranslation |
Export-Csv -Path 'yourCsvFile.csv' -NoTypeInformation

Note: The parentheses around the Import-Csv command are important, if you want to write back to the same file in a single pipeline. However, this holds the entire file in memory, which may be a problem if your CSV is very large. If you want to stream one line at a time instead, you need to read and write from different files, then move the new file back over top of the original afterward.


Viewing all articles
Browse latest Browse all 13067

Trending Articles