2016-12-13 19 views
2

我对批处理文件很陌生,我试图做一些体面的高级工作,并试图找出如何识别和解析IPCONFIG中DNS服务器下的第二行/所有。如果答案相当先进,如果能够彻底解释,我将非常感激。这里是我的代码:从IPCONFIG/all,Windows批处理解析第二个DNS

@echo off 
setlocal enabledelayedexpansion 
set adapter=Ethernet adapter Local Area Connection 
set adapterfound=false 

for /f "usebackq tokens=1-4 delims=:" %%f in (`ipconfig /all`) do (
    set item=%%f 
    if /i "!item!"=="!adapter!" (
     set adapterfound=true 
    ) else if not "!item!"=="!item:DNS Servers=!" if "!adapterfound!"=="true" (
     rem echo DNS: %%g 
     set Globaldns=%%g 
     set adapterfound=false 
    ) 
) 
for /f "tokens=1-2 delims= " %%m in ("%Globaldns%") do set Globaldns=%%m 
echo DNS: %Globaldns% 

如果有人设置两个DNS服务器,我需要一种方法来拉第二个DNS地址,并将其存储在第二个变量,上面的代码是能拉的第一个DNS,但我还没有想出一个办法来拉秒。感谢您的帮助!!编辑: 另一条信息。这需要能够在Windows Vista到Windows 10之间运行,并且需要能够针对特定连接(我们只重新配置以太网设备,无线)因此,我们需要能够使用适配器的连接名称解析(即本地连接,以太网)。

+0

ipconfig输出很难解析,可能更容易与'wmic nicconfig list DNS/format:CSV' – LotPings

+0

请参阅编辑,我喜欢你的答案,但我需要一种方式樱桃图特定的连接,我不能切实使用适配器名称。有没有办法将连接名称添加到它? (即本地连接#,以太网#) – user7253664

+0

这对我来说很困难,因为我有不同的语言环境,所以我的命名不匹配。 getmac/fo csv/v'返回什么输出? – LotPings

回答

1

LotPings是对的,ipconfig输出很难解析。解析wmic输出可能更容易

看看分别Win32_NetworkAdapter classWin32_NetworkAdapterConfiguration class及其wmic aliasesNICNICCONFIG

对于第一次识别,请使用wmic NIC get /VALUE。请注意0​​开关并注意NetConnectionID属性:网络连接的名称,因为它出现在网络连接控制面板程序中。然后,解析从输出

wmic NIC where "NetConnectionID = 'Local Area Connection'" get Index, MACAddress 

得到Index属性(Windows网络适配器配置的索引号。被用于索引号时,有一个以上的配置可用)值到varible,例如_index和按如下方式使用它:

wmic NICCONFIG where "Index = %_index%" get /Value 

为了便于分析,可以缩小输出到只有所需的性能和改变格式csv,例如

set "_properties=DefaultIPGateway,DHCPServer,DNSServerSearchOrder,IPAddress,IPSubnet" 
wmic NICCONFIG where "Index = %_index%" get %_properties% /format:CSV 

请注意,并应用戴夫·贝纳姆的WMIC and FOR /F: A fix for the trailing <CR> problem

编辑:固定一个错误用path关键字:

  • NIC      wmic别名path Win32_NetworkAdapter
  • NICCONFIGwmic别名path Win32_NetworkAdapterConfiguration

所以例如接下来的命令表示相同˙WQL˙ query

wmic NICCONFIG        where "Index = %_index%" get /Value 
wmic path Win32_NetworkAdapterConfiguration where "Index = %_index%" get /Value 
+0

当我使用正确的索引号而不是变量运行“wmic path NICCONFIG where”索引=%_index%“get/Value”命令时,除非我删除路径,否则它将出错。路径做什么? – user7253664

+0

@ user7253664答案固定,抱歉给您带来不便。 – JosefZ

+0

如何才能解析“wmic NIC”的输出,其中“NetConnectionID ='本地连接'”获取索引,MACAddress“只是索引? – user7253664

1

没有直接回答这个问题,但这个PowerShell脚本也许会有帮助,尽管我不知道这是否会下班回来到Vista。

gwmi Win32_NetworkAdapter -filter "netconnectionid is not null"| 
    %{ gwmi Win32_NetworkAdapterConfiguration ` 
    -filter "interfaceindex=$([int]$_.interfaceindex)"| 
     select -expandproperty DNSServerSearchOrder} 

因为我只配置了一个dns服务器,所以我的结果是正确的但没有意义。

+0

看来,OP想要只能获得有线连接的信息。是否有一个属性可以揭示这一点? – lit