简体   繁体   中英

Ping test batch file not working?

I have been working on a simple little project, but the batch code refuses to work. Can anyone help fix this? It either tells me that the ip must be specified or the ping result just doesn't show up.

@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
)
  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. Mixed CALL :Pingtest with reaching the :Pingtest label by normal code pass.

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

  3. A successful/unsuccessful PING does NOT always return an %errorlevel% of 0 / 1 . Therefore to reliably detect a successful ping - pipe the output into FIND and look for the text " TTL "

Hence, use

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

You need to enable delayed expansion for your code to work since you are assigning and reading a variable inside of a code block:

setlocal EnableDelayedExpansion

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

In addition you need to move the :PINGTEST section outside of the if %whatapp% block to the very end of your script, and place a goto :EOF before it to not fall into it unintentionally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM