0

I'm trying to get a batch file to display ping results while logging to a text file simultaneously. I found the following solution: https://stackoverflow.com/a/32185695/13321999. This does exactly what I need when everything is connected, however I found the command prompt window/batch file will simply close if there is a network disconnection resulting in a "general failure" (simulated by just unplugging my Ethernet cable). I'm hoping to get the output to look something like this:

Target Host = www.google.com 
Pinging www.google.com [172.217.9.36] with 32 bytes of data: 
Wed 04/15/2020 11:01:54 Reply from 172.217.4.196: bytes=32 time=46ms TTL=55
Wed 04/15/2020 11:01:55 Reply from 172.217.4.196: bytes=32 time=29ms TTL=55
Wed 04/15/2020 11:01:56 General failure.
Wed 04/15/2020 11:01:57 General failure.
Wed 04/15/2020 11:01:58 Reply from 172.217.4.196: bytes=32 time=29ms TTL=55
Wed 04/15/2020 11:01:59 Reply from 172.217.4.196: bytes=32 time=30ms TTL=55
Wed 04/15/2020 11:02:01 Request timed out.
Wed 04/15/2020 11:02:04 Request timed out.
Wed 04/15/2020 11:02:05 General failure.
Wed 04/15/2020 11:02:06 Reply from 172.217.4.196: bytes=32 time=31ms TTL=55

For reference the code I'm using is below, which is copied from the linked post. I would have just left a comment but I'm not cool enough yet.

echo off

set /p host=host Address: 
set logfile=Log_%host%.log

echo Target Host = %host% >%logfile%
for /f "tokens=*" %%A in ('ping %host% -n 1 ') do (echo %%A>>%logfile% && GOTO Ping)
:Ping
for /f "tokens=* skip=2" %%A in ('ping %host% -n 1 ') do (
    echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% %%A>>%logfile%
    echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% %%A
    timeout 1 >NUL 
    GOTO Ping)

Any change there is a way to handle these errors in the batch file so it doesn't crash?

snoozer
  • 1
  • 1

1 Answers1

0

After some more tinkering I found a solution for my own use case. It doesn't really "handle" errors in the conventional sense, but it allows the script to keep running. I simply added a timestamp after the for loop with "Error" though you can add whatever error message you like, a pause and a GOTO to try again. Figured I'd post what I did in case anyone else finds it useful, even though it's quite obvious in hindsight.

echo off

set /p host=host Address: 
set logfile=Log_%host%.log

echo Target Host = %host% >%logfile%
for /f "tokens=*" %%A in ('ping %host% -n 1 ') do (echo %%A>>%logfile% && GOTO Ping)
:Ping
for /f "tokens=* skip=2" %%A in ('ping %host% -n 1 ') do (
    echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% %%A>>%logfile%
    echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% %%A
    timeout 1 >NUL 
    GOTO Ping)

echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% Error>>%logfile%
echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% Error
timeout 1 >NUL
GOTO Ping
snoozer
  • 1
  • 1