Simple batch for checking internet connectivity and setting environment variable %internet% depending on result

With a tweak, your original code will work.

echo checking internet connection
Ping www.google.nl -n 1 -w 1000
cls
if errorlevel 1 (set internet=Not connected to internet) else (set internet=Connected to internet)

echo %internet%

The issue is that IF ERRORLEVEL n is TRUE if errorlevel is n or greater than n. IF ERRORLEVEL 0 is therefore always true. IF NOT ERRORLEVEL 1 is a test for errorlevel=0. So is IF %ERRORLEVEL%==0, except that the former can be used within a block but the latter cannot.

Nence, your code was setting not connected but the following line, since the if condition is always true, overwrites the value with the second message.

Note that set "%internet%"=="Connected to internet" means "set a variable, the name of which is stored in the variable internet to the value"

Hence, if internet had a value of fred at that time, then fred would be set to the value, not internet.

Furthermore, Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

Thus, since you are setting internet with a block (the if - true statement sequence, then you need to use one of the two common ways to overcome this. 1) use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values. A method technically related to the second is to use the statement call echo %%internet%% to display the changed value of internet within a block.


Another option...

ping -n 2 -w 700 10.11.1.1 | find "bytes="
IF %ERRORLEVEL% EQU 0 (
    SET internet=Connected to the internet.
) ELSE (
    SET internet=Not connected to the internet.
)
echo %internet%

This works well because...

  • Sometimes the return for ping is Reply from 10.11.1.106: Destination host unreachable. and since it has an errorlevel of zero this fails. (at least for me)
  • ping -n 2 will still pass if there happens to be a dropped packet.