-1

I want to replace all content of column A of a CSV with current date MMddyyyy using PowerShell command(s)

Looked over plenty examples over past couple days, but cant find the right answer, somewhat new to powershell, having a unix background for 35 years!

my desired results would be a new CSV file with date in 1st column followed by all the other columns from source CSV.

MMddyyyy, all, other, fields, from, original, csv

RussT
  • 1
  • also wouldn't mind doing it in perl if easier :) – RussT Apr 04 '19 at 14:33
  • 2
    Possible duplicate of [Add Column to CSV Windows PowerShell](https://stackoverflow.com/questions/17022017/add-column-to-csv-windows-powershell) – vonPryz Apr 04 '19 at 14:40

1 Answers1

1

Assuming your data is in a file called your.csv and the contents are as follows:

ColA,ColB,ColC
somethingA,somethingB,SomethingC
somethingA,somethingB,SomethingC
somethingA,somethingB,SomethingC
somethingA,somethingB,SomethingC
somethingA,somethingB,SomethingC
somethingA,somethingB,SomethingC

An efficient way to do this is following a solution posted at Add Column to CSV Windows PowerShell. Here are the details following that method where you want to replace the first column and keep the remaining columns in order:

Import-Csv your.csv | 
  Select-Object -Property @{n="ColA";e={get-date -f MMddyyyy}},* -ExcludeProperty ColA |
    Export-Csv new.csv -NoTypeInformation

A less efficient alternative processes each row and makes the appropriate change. This will update the original $file variable with the new data, but will leave the original file unchanged. new.csv is the output file with all of the updates.

$file =  Import-Csv your.csv

Foreach ($row in $file) {
   $row.ColA = get-date -f MMddyyyy
}

$file | Export-Csv new.csv -NotypeInformation

Now, the contents of new.csv are as follows:

"ColA","ColB","ColC"
"04042019","somethingB","SomethingC"
"04042019","somethingB","SomethingC"
"04042019","somethingB","SomethingC"
"04042019","somethingB","SomethingC"
"04042019","somethingB","SomethingC"
"04042019","somethingB","SomethingC"
AdminOfThings
  • 23,946
  • 4
  • 17
  • 27
  • For static content added, a Select-Object ishould be more efficient. See [Possible Duplicate](https://stackoverflow.com/questions/17022017/add-column-to-csv-windows-powershell) –  Apr 04 '19 at 14:44
  • I made an update to reference that solution. Thanks – AdminOfThings Apr 04 '19 at 14:57