我试图制作一个批处理脚本,该脚本应该可以对站点执行ping操作,记录结果并在结果为负数时启动程序。这是对原始脚本(不是我的)的修改,可以找到here。域,IP和程序变量的值仅用于说明目的。设置为空后批处理脚本中未清空的变量
@echo off
cls
set domain=testsite.com
set IP=133.78.17.101
set program=c:\windows\notepad.exe
set output=c:\log.txt
set result=1
:Start
IF [%result%]==[] (
>>%output% echo -----------
start %program%
)
ECHO Pinging %domain%...
FOR /F "delims=" %%G in ('ping -n 1 %domain% ^| find "Reply"') DO SET result=%%G
IF NOT [%result%]==[] (
goto Success
) ELSE (
goto TryAgain
)
:TryAgain
ECHO %domain% unreachable. Trying again...
FOR /F "delims=" %%G in ('ping -n 1 %domain% ^| find "Reply"') DO SET result=%%G
IF NOT [%result%]==[] (
goto Success2
) ELSE (
goto TryIp
)
:TryIp
ECHO %domain% unreachable. Pinging %ip%...
FOR /F "delims=" %%G in ('ping -n 1 %IP% ^| find "Reply"') DO SET result=%%G
IF NOT [%result%]==[] (
goto SuccessDNS
) ELSE (
goto TestInternet
)
:TestInternet
ECHO %ip% unreachable. Testing internet connection.
FOR /F "delims=" %%G in ('ping -n 1 www.google.com ^| find "Reply"') DO SET result=%%G
IF NOT [%result%]==[] (
goto Success3
) ELSE (
goto NetDown
)
:Success
>>%output% ECHO Connected
>>%output% echo %date% %time% %result%
ping -n 3 127.0.0.1 > nul
goto Start
:Success2
>>%output% ECHO Connected with packet loss.
>>%output% echo %date% %time% %result%
set result=
ping -n 3 127.0.0.1 > nul
goto Start
:Success3
>>%output% ECHO Domain %domain% not reachable. Connected via IP.
>>%output% echo %date% %time% %result%
set result=
ping -n 3 127.0.0.1 > nul
goto Start
:SuccessDNS
>>%output% ECHO DNS problem.
>>%output% echo %date% %time% %result%
set result=
ping -n 3 127.0.0.1 > nul
goto Start
:NetDown
>>%output% ECHO No internet connection.
>>%output% echo %date% %time% %result%
set result=
ping -n 3 127.0.0.1 >nul
goto Start
我试图实现这一目标是 - 如果收到不是一个完美的答复ping请求的任何其他的脚本应该启动一个程序。为了确保这种情况发生,我每次都清除result
变量,而不是预期的ping响应。
即使在清空它之后,回应result
的值仍会返回1。
'%result%'和'%result'不一样。你有一个错误的'IF NOT [%result] == []('lines。 – Stephan
'%result%'改变'%result'的所有实例并重试! – Compo
@Stephan正确,纠正它,但仍然不按照我的预期工作 – FiddlingAway