Author Posts

August 7, 2017 at 3:56 pm

Hi,

i have a script that outputs a line of results to a CSV, i would like to add a date stamp to a column each time the entry is created.

Any ideas?

thanks

Tommy.

August 7, 2017 at 10:07 pm

This is what I use:

$TimeStamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')>/pre>

August 8, 2017 at 9:35 am

Thanks Don. I've already got that part, but what im trying to do is to add the value into the csv along side the export-csv.
So kinda like

Do-Something | Export-CSV including $DateTime. 

cheers

August 8, 2017 at 10:31 am

I created a csv with a column of names in column 1 (heading name) then ran the following which creates another csv but with the date time in column 2

$obj=@()
$results=@()
$Userlist=Import-Csv "c:\test\name.csv"
Foreach ($user in $userlist)
{
$obj = New-Object System.Object
$obj | Add-Member -MemberType NoteProperty -name 'Username' -value $User.name
$obj | Add-Member -MemberType NoteProperty -name 'date' -value (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
$results += $obj
}

$results | export-csv c:\test\withdate.csv

August 8, 2017 at 11:49 am

Do-Something | Add-Member -MemberType NoteProperty -Name Timestamp -Value (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') -Passthru | export-csv -path myfile.csv

Hope this helps
/fridden

August 8, 2017 at 12:55 pm

This generates an example of your single liner (single column) CSV:

$myCSV = '.\mydatatest.csv'
0..9 | % { [PSCustomObject]@{ Data = "bla$_" } } | # Example of your existing 10 lines of data
    Export-Csv $myCSV -NoType                      # Saved to CSV

This adds a 'TimeStamp' column to existing rows:

$myData = Import-Csv $myCSV |                                                 # Read data from CSV
    Add-Member -MemberType NoteProperty -Name 'TimeStamp' -Value '' -PassThru # Add TimeStamp column
$myData | Export-Csv $myCSV -NoType                                           # Save it back to CSV

Example code for future time stamped entries:

$newEntry = [PSCustomObject]@{ 
    Data      = "bla and some $Variables" 
    TimeStamp = Get-Date -Format 'ddMMMMyyyy_hh-mm-ss_tt'
}
$newEntry | Export-Csv $myCSV -NoType -Append