我試圖製作一個批處理腳本,該腳本應該可以對站點執行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