在bat脚本中将ping从ping中提取到变量中

时间:2013-06-14 06:39:05

标签: windows batch-file cmd ip

无论如何我能做到这一点?

@echo off
REM #Testing FIND in IPCONFIG

setlocal EnableDelayedExpansion

for /f "tokens=3" %%a in ('ping localhost ^| findstr /i "reply"') do (
  set address=%%a
  set address=!address::=!
)

ipconfig /all | findstr %address%
if ERRORLEVEL = 1 goto VIP_NOT_FOUND

REM #We are here becuase the find returned a result.
REM #It is safe to execute the rest of the application.
REM #EXECUTES THE SCRIPT HERE

echo "testing works" >> testing.txt

:VIP_NOT_FOUND
REM #This part of the script is where you would handle any
REM #error logging or other admin related
echo "Could not find a VIP. - Exiting"
echo "end of script reached."

我在Windows Server 2k8 ENG版本上运行此脚本。它似乎继续给我发现:错误的命令行。但我不确定问题出在哪里。

1 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

@echo off

setlocal EnableDelayedExpansion

for /f "tokens=3" %%a in ('ping myhost.com ^| find /i "reply"') do (
  set address=%%a
  set address=!address:~0,-1!
)

ipconfig /all | findstr "%address%" >nul && (
  rem Do stuff
)

如果主机有IPv4地址和IPv6地址,并且您正在寻找IPv4地址,请使用ping -4而不是ping