Sehaj Paul Singh
Sehaj Paul Singh

Reputation: 55

I want to add a time and date column to a csv file using powershell

I want to add time and date row at the end of each entry in the csv file. I am only able to add time and date at the end of the database not to each row

Powershell

import-csv C:\Users\system\Desktop\WindowsUpdate1.csv | 
  foreach-object {
    $row = $_
    $row | add-member NoteProperty "Time" (Get-Date -format t) 
    $row 
  }

I only get one column in regard to the date and time instead of getting it in every row.

Upvotes: 3

Views: 2506

Answers (1)

Theo
Theo

Reputation: 61068

As Lee_Dailey commented, the easiest way is to use the Select-Object cmdlet with a calculated property:

$newCsv = Import-Csv 'C:\Users\system\Desktop\WindowsUpdate1.csv' | 
    Select-Object *, @{Name = 'Time'; Expression = {(Get-Date -format s)}}

#output on screen
$newCsv

#output to new csv file
$newCsv | Export-Csv 'C:\Users\system\Desktop\WindowsUpdate2.csv' -NoTypeInformation

I have changed your date/time format from (Get-Date -format t) to (Get-Date -format s) in order to get a sortable date/time format because the title of the post asks for date AND time. See Standard Date and Time formats for more formats

Upvotes: 2

Related Questions