4

I want to prepend a timestamp to each line of output from a command. For example:

foo
bar
baz

would become:

[2011-12-13 12:20:38] foo
[2011-12-13 12:21:32] bar
[2011-12-13 12:22:20] baz

where the time being prefixed is the time at which the line was printed. How can I achieve this with PowerShell?

runamuk0
  • 784
  • 1
  • 7
  • 20
  • Not sure why the question was down-voted. You have my +1. – avakar Oct 28 '17 at 15:09
  • 1
    @avakar I downvoted it; hover over the downvote arrow and the tooltip popup says that downvotes are for questions which show no research effort. Questions which are just statements "I need x" almost always gets a downvote from me, regardless of whether I try to comment or answer helpfully or not, because that's the design of the site. – TessellatingHeckler Oct 29 '17 at 00:48

2 Answers2

7

Assuming your command is a external command named foo, you can pipe it's output through a ForEach-Object to add the timestamp:

foo | ForEach-Object { "$(Get-Date -Format "[yyyy-MM-dd HH:mm:ss]") $_" }

Burt_Harris
  • 6,415
  • 2
  • 29
  • 64
3

You can make it a named column with something like:

x.exe |Select @{Name='XTime';Expression={"[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $_"}}
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87