I'm trying to use a batch file to confirm a network connection using ping. I want to do batch run and then print if the ping was successful or not. The problem is that it always displays 'failure' when run as a batch. Here is the code:
@echo off
cls
ping racer | find "Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),"
if not errorlevel 1 set error=success
if errorlevel 1 set error=failure
cls
echo Result: %error%
pause
'racer' is the name of my computer. I'm having my computer ping itself so I can eliminate the variable of a poor connection. As I said before, the batch always results in failure. Oddly enough, the program works fine if I copy the code into the command prompt. Does anyone know why the program works fine in the command prompt but doesn't work as a batch? Thanks
I needed to reset a wifi connection because it has issues. This was my quick solution.
@echo off Rem Microsoft Windows 10 ping test to gateway. Rem Run batch file from an administrative command prompt.
cls :starting Rem Send one ping to the gateway. Write the results to a file. ping 192.168.1.1 -n 1 > pingtest.txt
Rem Search for unreachable in the file. c:\windows\system32\findstr.exe "unreachable" pingtest.txt
Rem errorlevel 0 reset the adapter if 1 then wait 10 minutes and test again if %errorlevel%==1 goto waiting
Rem unreachable was found reset the adapter.
Rem write the date and time the reset was done. echo Reset date: %date% time: %time% >> resettimes.txt
Rem issue netsh interface show interface to find your adapter's name to reset Rem my adapter is "wi-fi"
netsh interface set interface "wi-fi" disable timeout /t 5 netsh interface set interface "wi-fi" enable :waiting echo "It is online waiting 10 minutes" timeout /t 600 goto starting
Another variation without using any variable
ErrorLevel
is0
if example.com is online,1
otherwise.NOTE: Tested on Win8 only!
Yes ping fails to return the correct errorlevel. To check the network connection and the computer I used "net view computername" then checked %errorlevel% - simple and easy
Based on Alex K's note, this works for me on Windows 7:
If you were to
you would see the
%
is stripped. You need to escape it as%
has a special meaning within a batch file:However its simpler to use TTL as the indication of success;