Windows Powershell Rename CSV Column Header File

Sorry to post this, but I can't figure out how to do such a basic thing, how to rename a column header in a csv file using windows powershell. I can add new ones, delete, fill out, export, but I can’t find out how to change the title.

I thought it was possible to import the CSV and export with the specified header, but it does not work:

import-csv c:\tmp\test.csv | Select-Object first_name | Export-Csv -header "test" c:\tmp\test1.csv 

I basically need to reformat the CSV file, so if I can select the data I need and specify new headers that would be ideal.

Of course, this should be straightforward. I have to miss something obvious ....

+7
source share
3 answers

You can use Select-Object with a calculated property for this.

  Import-Csv test.csv | Select-Object @{ expression={$_.first_name}; label='test' } | Export-Csv -NoTypeInformation test1.csv 
+11
source

Can you try something like:

 import-csv 'c:\tmp\test.csv' | select -Property @{name="test";expression={$($_.first_name)}}| Export-Csv c:\tmp\test1.csv 
+8
source

I know that there is already an answer to this, but here is another method when you need to change one (or several) columns without the need for hard coding of each column.

 function Convert-Object($rec){ $object = New-Object System.Object $members = ($rec[0].psobject.Members | ?{$_.MemberType -match "Property"}).Name.Trim() foreach($mem in $members){ if($mem -eq 'File Number'){ $object | Add-Member -MemberType NoteProperty -Name "FileNumber" -Value $rec.'File Number' }else{ $object | Add-Member -MemberType NoteProperty -Name $mem -Value $rec.$mem } } return $object } $convCSV = ($CSVs | ?{$_.Name -match "YourCsvName"}).FullName #multiple CSVs perhaps $toConvert = Import-Csv $convCSV $convObjs = New-Object System.Collections.ArrayList $toConvert | foreach{$convObjs += Convert-Object -rec $_} $convObjs | Export-Csv $convCSV -NoTypeInformation 
0
source

All Articles