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

Ping test batch file not working?

我一直在做一个简单的小项目,但批处理代码无法运行。谁能帮忙解决这个问题?它要么告诉我必须指定 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
)

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

setlocal EnableDelayedExpansion

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

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

  1. EnableDelayedExpansion

Delayed Expansion will cause variables to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL command. When delayed expansion is in effect variables can be referenced using !variable_name! (in addition to the normal %variable_name%)

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

  2. 使用 GOTO or even :label within parentheses - including FOR and IF commands - will break their context.

  3. A successful/unsuccessful PING 并不总是 return %errorlevel% of 0 / 1。 因此 to reliably detect a successful ping - 将输出通过管道传输到 FIND 并查找文本“TTL

因此,使用

@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
)