使用BAT文件的PING测试 - 与ERROLEVEL的麻烦



我正在努力使用批处理文件设置LAN PING测试。我拥有的代码非常适合网站,但对于本地IP来说很奇怪。我正在在3台我知道的IPS的3台计算机上运行PING测试。无论我拔下哪一个,当我运行下面的代码时,%errorlevel%始终在所有三台计算机上始终为0。它永远不会像在网站上那样等于1。我该如何解决?

@echo off
cls
Set IPaddress=www.google.com
PING %IPaddress% -n 1
 call :PingTest
Set IPaddress=www.yahoo.com
PING %IPaddress% -n 1
 call :PingTest
Set IPaddress=www.unabletoping.com
PING %IPaddress% -n 1
 call :PingTest
pause > null
exit
:PingTest
IF %errorlevel% EQU 1 (echo "Server is Offline") else (GOTO:EOF)

当您在子网中ping一个不可接受的地址时,您会得到一个"无法到达的"答案,并发送了1个数据包,1包,收到1个包装,丢失了0个数据包。未设置ErrorLevel。

当您从子网中ping一个不可接受的地址时,您会得到一个"超时"答案,并发送1个数据包,收到0个数据包,丢失了1个数据包。设置了ErrorLevel。

,您可以ping ping机器,丢失数据包并获取错误级别

,您可以ping ping ovition/intactive机器,使TTL过期,没有错误级别

更好,检查ping响应的内容。

ping -n 1 192.168.1.1 | find "TTL=" >nul
if errorlevel 1 (
    echo host not reachable
) else (
    echo host reachable
)

虽然我无法复制您的问题,但我确实有一些建议。(有关此问题的问题,请参阅我的评论)

  1. 创建变量封装范围时。setlocalendlocal
  2. 退出脚本时,请使用/b标志以不杀死呼叫者的命令提示。
  3. nul not null。

示例():

@echo off
setlocal
cls
set "IPaddress=www.google.com"
call :PingVerbose "%IPaddress%"
call :PingVerbose "www.yahoo.com"
call :PingVerbose "www.microsoft.com"
pause>nul
endlocal
exit /b 0
:Ping <Address>
ping "%~1" -n 1 >nul
exit /b %ErrorLevel%
:PingVerbose <Address>
call :Ping %1 && echo %~1 is Online || echo %~1 is Offline
exit /b %ErrorLevel%

尽管我也无法复制您的问题,并且也有一个建议可以更好地脚本 -

@echo off & cls
set addresses=10.1.1.666 10.124.412.14 10.7.254.1
for %%a in (%addresses%) do ping %%a -n 1 > nul || echo %%a is offline

请注意,仅当Ping设置错误级别时,||之后的命令才能执行。

采用其他人提到的内容,我想展示一个人可能需要做上面显示的所有内容以及使用修改变量(例如循环中的计数器)。

注意:使用" setLocal eneabledelayedExpansion"允许在循环中使用修改变量等。

@echo off
setlocal enabledelayedexpansion
REM List of systems to check
set list=www.google.com www.yahoo.com www.notasite.com
set /a failed=0
set /a passed=0
set /a count=0
echo PingTest Servers on %list% :
(for %%a in (%list%) do ( 
    set /a "count+=1"
    call :PingVerbose %%a && set /a "passed=!passed!+1" || set /a "failed=!failed!+1"
))
echo ------------
echo Result: %passed% of %count% systems are pingable
pause
endlocal
exit /b 0
:Ping <Address>
ping "%~1" -n 1 >NUL
exit /b %ErrorLevel%
:PingVerbose <Address>
call :Ping %1 && echo %~1 - [ONLINE] || echo %~1 - [OFFLINE] 
exit /b %ErrorLevel%

输出:

PingTest Servers on www.google.com www.yahoo.com www.notasite.com :
www.google.com - [ONLINE]
www.yahoo.com - [ONLINE]
www.notasite.com - [OFFLINE]
------------
Result: 2 of 3 systems are pingable
Press any key to continue . . .         

最新更新