我写的这个脚本旨在从WMIC中解析并提取IP信息。问题在于,当它在只有一个DNS服务器输入的计算机上使用时,脚本会失败。它似乎即使变量DNS2未设置也运行:remove函数,然后:remove函数以我不熟悉的方式失败,并忽略退出命令并跳出函数进入我不想要的脚本部分。以下是有问题的代码,请通过设置您的DNS服务器和索引来测试。脚本需要定义2个DNS服务器才能正常工作,而只有1个则无法正常工作。
@echo off
setlocal enabledelayedexpansion
SETLOCAL ENABLEEXTENSIONS
wmic NICCONFIG where "Index = 1" get /Value | more > storage.txt
for /f "tokens=1-9 delims=,}{=" %%f in (storage.txt) do (
set cat=%%f
IF /i !cat!==IPAddress (set IP=%%g)
IF /i !cat!==IPSubnet (set SUB=%%g)
IF /i !cat!==DefaultIPGateway (set GW=%%g)
IF /i !cat!==DNSServerSearchOrder (
set DNS=%%g
set DNS2=%%h
)
IF /i !cat!==IPEnabled (set enabled=%%g)
IF /i !cat!==Description (set desc=%%g)
)
if /i %enabled%==True (
if defined IP (
set item=IP
CALL :remove
)
if defined SUB (
set item=SUB
CALL :remove
)
if defined GW (
set item=GW
CALL :remove
)
if defined DNS (
set item=DNS
CALL :remove
)
if defined DNS2 (
set item=DNS2
CALL :remove
)
)
goto :menu
echo SHOULDN'T BE HERE
pause
:::::::::Function to remove quotes::::::::::::::
:remove
for /f tokens^=1^ delims^=^" %%p in (!%item%!) do (
set !item!=%%p
rem echo !%item%!
EXIT /b
)
echo I BROKE OUT OF THE FUNCTION
pause
:menu
echo I worked!
echo %IP%
echo %SUB%
echo %GW%
echo %DNS1%
if defined DNS2 ( echo %DNS2% )
pause
这里有一个使用LotPings重新设计的另一个例子,需要注意的是,即使没有DNS2,它仍然执行底部的“if defined”语句。
@echo off
SETLOCAL ENABLEEXTENSIONS enabledelayedexpansion
Set Prop=IPAddress IPSubnet DefaultIPGateway DNSServerSearchOrder IPEnabled Description
for /f "tokens=1-9 delims=,}{=" %%f in (
'wmic NICCONFIG where "Index = 1" get /Value^|findstr /i /B "%Prop%"'
) do (IF /i %%f==IPAddress set "IP=%%~g"
IF /i %%f==IPSubnet set "SUB=%%~g"
IF /i %%f==DefaultIPGateway set "GW=%%~g"
IF /i %%f==DNSServerSearchOrder (
set "DNS=%%~g"
set "DNS2=%%~h"
)
IF /i %%f==IPEnabled set "enabled=%%~g"
IF /i %%f==Description set "desc=%%~g"
)
set|Findstr /i /B "IP SUB GW DNS Ena Desc"
echo I worked!
echo %DNS%
echo %DNS2%
if defined DNS2 ( echo DNS2 found, shouldn't have found this)
pause
for
的选项(tokens,delims)缺少一个开头的双引号。 - Mike Nakis