Chinmay Nayak
Chinmay Nayak

Reputation: 273

Unable to add an extra column to an existing CSV file

I have a .csv file which contains data as below:

Name ID
ABC 1234
CDE 3456

I am trying to insert a column called "Date" as the first column.

Date        Name     ID
2018-03-28  ABC     1234
2018-03-28  CDE     3456

I am using below import-export:

$a = Import-Csv -Path c:\filename.csv -Header Date,Name,Id
$a | Export-Csv -Path c:\outfile.csv -NoTypeInformation

But above not working as expected. It's displacing the column data.

Date  Name  Id
ABC   1234
CDE   3456   

Upvotes: 1

Views: 3001

Answers (2)

Vivek Kumar Singh
Vivek Kumar Singh

Reputation: 3350

You can make use of calculated properties like this -

Import-Csv -path C:\filename.csv |
Select-Object *,@{Name='Date';Expression={'2018-03-28'}} | 
Select-Object Date, Name, ID |
Export-Csv -path C:\Outfile.csv -NoTypeInformation

Upvotes: 3

EBGreen
EBGreen

Reputation: 37830

You need to add the property to the objects:

$a= import-csv -path c:\filename.csv -header Name,Id
foreach($item in $a){
    Add-Member -Input $item -MemberType NoteProperty -Name Date -Value '2018-03-28'
}
$a | Select-Object Date, Name, ID | export-csv -path c:\outfile.csv -Notypeinformation

Upvotes: 2

Related Questions