在批处理中,如何创建一个IF语句来检查变量是否包含特定的字符串或数据?

时间:2014-03-10 15:32:02

标签: batch-file

我想批量制作一个基本的pinger作为我的学习项目,我遇到了一个问题。这是代码:

@echo off
color B
title Pinger v1.0 
:OK
echo.
echo.
set /p t=Target I.P.:
echo.
echo.
echo This is not an IP address!
echo.
goto OK
set /p a=Packet size:
echo.
:start
set ifer=
set /p ifer=Start Ping (y/n):
if %ifer%==y goto 8
if %ifer%==Y goto 8
if %ifer%==n goto OK
if %ifer%==N goto OK
:8
echo.
echo.
echo.
echo.
ping %t% -t -l %a%

我的问题是,如何检查t是否包含有效的IP地址而不是某些随机数据? 而且,我如何制作一个将网址转换为IP地址的代码(尽管不必回答这个问题)

1 个答案:

答案 0 :(得分:0)

我不知道您要在这里做什么。我编写了一个程序,该程序将使用您的IP或主机名,并根据用户确定的数据包大小和ping的次数对它进行ping。我只尝试了1.1.1.1和www.google.com,但它对其他任何功能都适用。

@echo off
@title Pinger v1.1

color B
setlocal EnableDelayedExpansion

:ipInput
cls
set /p tryIP=Target IP:
:: pinging ip once (-n 1) with one byte of data (-l 1) to check if it's valid
ping -n 1 -l 1 !tryIP! >nul & if errorlevel 1 ( 
    echo IP: !tryIP! is invalid, try correcting your input or using a different IP
    pause
    goto ipInput
)
cls
echo IP: !tryIP! is Valid
set /p pingCount=Enter number of pings:
set /p packets=Enter packet size:
echo Pinging !tryIP! with !packets! bytes for !pingCount! time^(s^)
:: You can either use this line (beneath)
REM ping -n !pingCount! -l !packets! !tryIP!


:: Or you can use this for loop from here.........
:: for /l indicates type of operation in this case it will take (start at, add or 
subtract by, end at)
:: %%a in this case, based on /l will always equal the number 
:: of times it's looped through..
:: (starting at 1, moving up by 1 each time, and ending after 32)
for /l %%a in (1,1,%pingCount%) do (
    ping -n 1 -l !packets! !tryIP! >nul
    cls
    echo Pinging !tryIP! with !packets! bytes for !pingCount! time^(s^)
    set /a percentage=%%a*10000/!pingCount!
    if !percentage! LSS 100 echo ......!percentage:~0,0!.!percentage:~0,2!%%
    if !percentage! GEQ 100 if !percentage! LSS 1000 echo ......!percentage:~0,1!.!percentage:~1,2!%%
    if !percentage! GEQ 1000 echo ......!percentage:~0,2!.!percentage:~2,2!%%
)
    :: the if statements are used to correct the formating on the percentages
    :: since batch can't use floating point decimals,
    :: you have to get a little creative sometimes.
    :: dual % signs are so it doesn't think you're trying to set a variable
    :: using ( or ) without that >>>^ (eg on lines 20 and 34) 
    :: will sometimes mess things up. 
:: ........ to here. the benefit of a for loop is that you can see your progress,
:: and it's much much faster as the ping command will wait between pings.
echo Done
pause
goto ipInput