Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add timestamp to log lines from batch output

I have a simple batch file that is scheduled to run, and essentially just backs up a remote network share to my computer.

@ECHO OFF
xcopy \\10.8.0.1\share\ E:\backup\ /c /s /r /d /y /i >> E:\backup\backup.log

The output in the log looks like this:

\\10.8.0.1\share\test.txt
1 File(s) copied
\\10.8.0.1\share\New Microsoft Word Document.docx
1 File(s) copied

Basically I just want to add a date and time stamp to each log entry. How do I go about doing this?

like image 419
user3608260 Avatar asked Sep 27 '16 04:09

user3608260


2 Answers

You could echo DATE% and %TIME% to backup.log.

echo %DATE% %TIME% >> E:\backup\backup.log

That's probably the easiest.

You could also use robocopy for richer logging options.

like image 68
soja Avatar answered Nov 18 '22 16:11

soja


The standard variables %date%and %time% are what you are looking for.

You can pass the lines of a command output as single lines with a for-loop and in between them

@echo off
for /f "delims=" %%i in ('xcopy \\10.8.0.1\share\ E:\backup\ /c /s /r /d /y /i') do (
    echo [%date%, %time%] %%i >> E:\backup\backup.log
)

Short explanation: The loop splits the output of the command to the single lines. For each line the program then echos the timestamp and after that one line of the output. Then it repeats for each line getting returned by the xcopy command.

like image 13
geisterfurz007 Avatar answered Nov 18 '22 16:11

geisterfurz007