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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…