0

I have a CSV file in which I want to change the headers names.

The current header is: name,id and I want to change it to company,transit

Following is what I wrote in script:

$a = import-csv .\finalexam\employees.csv -header name,id
foreach ($a in $as[1-$as.count-1]){  
    # I used 1 here because I want it to ignore the exiting headers.
    $_.name -eq company, $_.id -eq transit
}

I don't think this is the correct way to do this.

1
  • You could just use Get-Content and write a manual header with commas Commented Apr 10, 2015 at 20:07

2 Answers 2

1

You're over thinking this... All you want to do is replace the header row, so set the new header as the first item of an array, read in the file skipping the first line and add it to the array, output the array.

"Company,Transit"|Set-Content C:\Path\To\NewFile.csv
Get-Content C:\Path\To\Old.csv | Select -skip 1 | Add-Content C:\Path\To\NewFile.csv
Sign up to request clarification or add additional context in comments.

Comments

0

Something very simple like this:

$file = Get-Content C:\temp\data.csv
"new,column,name" | Set-Content C:\temp\data.csv
$file | Select-Object -Skip 1 | Add-Content C:\temp\data.csv

Collect the complete file contents and then write a new header. Then restore the rest of the file content while -skiping the original header.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.