Windows – Batch file to write ping results to a text file

batchbatch filepingwindows 7

I know this is a variation of an already asked question but after research and several failed attempts I think I need some help.

I would like to ping two websites repeatedly and record the time and results in a text file.

I found this question Save Ping Output in a text file to be very helpful but the several versions I have tried do not work.

If I execute the following in a command window, it creates the text file in my users directory as I would expect with the repeated pings recorded correctly.

ping xxx.xxx.xxx.xxx -t > filename.txt

But if I create the following ping.dat file and save it on my desktop. When I run it, it both opens a cmd window with the just time in it and also creates the desired textfile on my desktop. Unfortunately the file only contains the time and not the ping results and the results are obviously not 3seconds apart like expected.

@ECHO OFF
:LOOPSTART
time /T
ping xxx.xxx.xxx.xxx -n 4 >> filename.txt
ping yyy.yyy.yyy.yyy -n 4 >> filename.txt
sleep -m 3000
GOTO LOOPSTART

I assumed that my problem was related to how I was trying to write the results but if I modify the batch file, deleting the '>> filename.txt' reference all it does is open a cmd window which instantly fills up with time stamps.

@ECHO OFF
:LOOPSTART
time /T
ping xxx.xxx.xxx.xxx -n 4
ping yyy.yyy.yyy.yyy -n 4
sleep -m 3000
GOTO LOOPSTART

Hence my questions are

A) Any idea what I am doing wrong?

B) How do I change the time stamp so that it is HH:MM:SS rather than HH:MM

All help appreciated.

S.

@LInker3000 Thanks for the reply. I should have mentioned this in my original question, but I have already tried that. When I added '>> filename.txt' to the timestamp, I now get a command window that fills up with "The process cannot acces the file because it is being used by another process.". Upon terminating the process, the created txt file only has one timestamp and the "Terminate Batch Job (Y/N)" text.

Best Answer

If you want the timestamp in the file too, you'd need to put:

time /T >> filename.txt

In the first example you quoted:

@ECHO OFF
:LOOPSTART
time /T >> filename.txt
ping xxx.xxx.xxx.xxx -n 4 >> filename.txt
ping yyy.yyy.yyy.yyy -n 4 >> filename.txt
sleep -m 3000
GOTO LOOPSTART

You can play around with the following code to give you a more configurable timestamp:

set time_hh=%time:~0,2%
if %time_hh% lss 10 (set time_hh=0%time:~1,1%)
set time_mn=%time:~3,2%
set time_ss=%time:~6,2%
set time_ms=%time:~9,2%

echo %time_hh%:%time_mn%:%time_ss%.%time_ms% >> filename.txt

Put all of this in place of the time /t... line

Related Question