mzv
mzv

Reputation: 307

Powershell: can't generate current time in csv

$timestamp = get-date -format "d-M-yyyy-H-mm"

I fill a csv file with lines, every line has $timestamp in first column and 3 other values.

#script actions1
$line = "$timestamp;value1;value2;value3"
$line | out-file $file -encoding utf8 -append -force
#script actions2
$line = "$timestamp;value1;value2;value3"
$line | out-file $file -encoding utf8 -append -force

When I open the csv file, I see that every string has the same date and time which cannot be true. The csv sample looks like this:

"22-12-2014-12-00;value1;value2;value3"
"22-12-2014-12-00;value1;value2;value3"
"22-12-2014-12-00;value1;value2;value3"

How can i write the current time of each event in my log?

Upvotes: 0

Views: 63

Answers (1)

Micky Balladelli
Micky Balladelli

Reputation: 9991

When you define $timestamp = get-date -format "d-M-yyyy-H-mm", you are basically saving the current time in the given format in the variable $timestamp

Then when you store the variable $timestamp in the file, you are saving the value at the time of the execution of Get-Date, not the current time.

If you want to capture the current time and date at the moment of saving to the file do this:

"$(get-date -format "d-M-yyyy-H-mm");value1;value2;value3" | out-file $file -encoding utf8 -append -force

PS. with that format you are not saving the seconds, so unless you execute the various scripts by giving sufficient time between functions, time will be the same. You can use this format to save the seconds "d-M-yyyy-H-mm-s"

Upvotes: 2

Related Questions