Chris
Chris

Reputation: 219

How to dynamically append time in a file using Powershell

Hopefully I worded that title correctly.

Transcript files don't show the info I want and I need to be able to see specific events at a glance, so I am adding an additional file that I am using as a log file.

I want to have the time appended at the beginning of each line, but it simply takes the the time it retrieved at the beginning of the script and uses that over and over again.

Script:

start-transcript -path "C:\temp\transcript  $(get-date -f dd-MM-yyyy).txt"
$log = "c:\temp\log $(get-date -f dd-MM-yyyy).txt"
$logtime = Get-Date -Format "hh:mm:ss"

Write-output "$logtime First line" | add-content $log
start-sleep -s 60
Write-output "$logtime Second line" | add-content $log

stop-transcript
exit

This is the output that I get, even though it sleeps for a full minute:

02:43:52 First line
02:43:52 Second line

There may very well be no way to do this, but thought I would give it a shot anyways.

Thanks for any help.

Upvotes: 1

Views: 3755

Answers (3)

Kory Gill
Kory Gill

Reputation: 7163

Write a function for what you want to do.

function Write-Log1 ($message, $logfile)
{
    $logtime = Get-Date -Format "hh:mm:ss"
    Write-Output "$logtime $message" | Add-Content $logfile
}

function Write-Log2 ($message)
{
    $logfile = Join-Path "c:\temp\log" "$(get-date -f dd-MM-yyyy).txt"
    $logtime = Get-Date -Format "hh:mm:ss"
    Write-Output "$logtime $message" | Add-Content $logfile
}


# call like this:

Write-Log1 "First line" $log
Write-Log1 "Second line" $log

# if you want, hard code the log inside the function

Write-Log2 "First line" $log
Write-Log2 "Second line" $log

I am sure with some searching, you can find more elaborate and complete examples of a similar pattern.

Upvotes: 1

Chris
Chris

Reputation: 219

Final code, thanks to "Willcodeforfun":

start-transcript -path "C:\temp\transcript  $(get-date -f dd-MM-yyyy).txt"
$log = "c:\temp\log $(get-date -f dd-MM-yyyy).txt"

$logtime = Get-Date -Format "hh:mm:ss"
Write-output $logtime "First line" | add-content $log
start-sleep -s 60
$logtime = Get-Date -Format "hh:mm:ss"
Write-output $logtime "Second line" | add-content $log

stop-transcript
exit

While I feel that this kind of defeats the purpose of variables and is painful to add through my entire script (looks messy), it does the job and makes the end result neat and easy to read.

The above is not taking a shot at "Willcodeforfun", but is taking a shot at Powershells inability to use a variable to get the real current time.

Upvotes: 1

Willcodeforfun
Willcodeforfun

Reputation: 361

Can you assign this to $logtime each time you want to output it instead?

$logtime = [System.DateTime]::Now

This method promises to get current time.

Edited to remove the suggestion that you re-assign to Get-Date each time since that didn't work for you.

Upvotes: 2

Related Questions