Ping测试批处理文件不起作用?

时间:2015-10-12 07:27:40

标签: windows batch-file cmd ping

我一直在研究一个简单的小项目,但批处理代码拒绝工作。谁能帮忙解决这个问题?它要么告诉我必须指定ip,要么ping结果不会显示。

@echo off

echo       :1 Minecraft server resolver 
echo       :2 Website resolver
echo       :3 Ping test
echo       :4 Crash this computer
echo       Please enter your selection 
set /p whatapp=
cls

if %whatapp%==1 (
    echo         Please enter the IP of the Minecraft server you wish to resolve   
    set /p x=IP=
    set n=1
    PING %x% -n 1
    call :Pingtest 
    pause > nul
:Pingtest
    IF %errorlevel% EQU 1 (echo Server is Offline) else (GOTO:EOF)
    pause
) else if %whatapp%==2 (
    codetoinstallapp2
) else (
    echo invalid choice
)

2 个答案:

答案 0 :(得分:2)

  1. EnableDelayedExpansion
  2.   

    延迟扩展将导致变量在执行时扩展   时间而不是在解析时,这个选项打开了   SETLOCAL命令。当延迟扩展实际上变量可以   使用!variable_name!引用(除了正常情况   %variable_name%

    1. 混合CALL :Pingtest,通过正常的代码传递达到:Pingtest标签。

    2. 使用GOTO or even :label within parentheses - 包括FORIF命令 - will break their context

    3. 成功/失败的PING并不总是会返回%errorlevel% / 0 1。 因此to reliably detect a successful ping - 将输出传输到FIND并查找文字“TTL

    4. 因此,请使用

      @echo OFF
      SETLOCAL EnableExtensions EnableDelayedExpansion
      color 02
      echo(---
      echo       :1 Minecraft server resolver 
      echo       :2 Website resolver
      echo       :3 Ping test
      echo       :4 Crash this computer
      echo       Please enter your selection 
      set /p whatapp=
      cls
      
      if %whatapp%==1 (
        cls
        color 02
        echo( ---
        echo         Please enter the IP of the Minecraft server you wish to resolve   
        set /p x=IP=
        set n=1
        PING !x! -n 1|FIND /I "TTL="
      REM   call :Pingtest 
      REM   pause > nul
      REM   :Pingtest
        echo !errorlevel!
        IF !errorlevel! EQU 1 (echo Server !x! is Offline) else (
          echo Server !x! is Online
          rem next code here
          REM GOTO:EOF
        )
        pause
      
      ) else if %whatapp%==2 (
        codetoinstallapp2
      ) else (
        echo invalid choice
      )
      

答案 1 :(得分:0)

您需要启用delayed expansion才能使代码正常工作,因为您在代码块中分配和读取变量:

setlocal EnableDelayedExpansion

if %whatapp%==1 (
    set /p x=IP=
    ping !x! -n 1
)
endlocal

此外,您需要将:PINGTEST块之外的if %whatapp%部分移动到脚本的最末端,并在其前面放置一个goto :EOF,以免意外陷入其中。

相关问题