我对批处理文件很陌生,我正在尝试做一些相当高级的事情,并且正在尝试找出如何识别和解析 IPCONFIG/all 中 DNS SERVERS 下的第二行。如果答案相当先进,如果您能彻底解释一下,我将不胜感激。这是我的代码:
@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 的任何操作系统上运行,并且需要能够针对特定连接(我们只是重新配置以太网设备,没有无线),因此我们需要能够使用适配器的连接名称解析(即本地连接、以太网)。
最佳答案
LotPings是的,ipconfig
输出很难解析。解析wmic
输出可能更容易。
看看Win32_NetworkAdapter class和 Win32_NetworkAdapterConfiguration class和他们的 wmic
aliases NIC
和NICCONFIG
,分别。
首次识别时,请使用wmic NIC get /VALUE
。请注意/VALUE
切换并注意 NetConnectionID
属性:出现在网络连接控制面板程序中的网络连接名称。然后,解析
wmic NIC where "NetConnectionID = 'Local Area Connection'" get Index, MACAddress
获取Index
属性(Windows 网络适配器配置的索引号。当有多个可用配置时使用索引号)变量值,例如_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
请注意并应用 Dave Benham 的 WMIC
and FOR /F
: A fix for the trailing <CR>
problem .
编辑:修复了 path
的错误关键字:
-
NIC
是wmic
path Win32_NetworkAdapter
的别名 -
NICCONFIG
是wmic
path Win32_NetworkAdapterConfiguration
的别名
所以例如接下来的命令代表相同的 ˙WQL˙ query :
wmic NICCONFIG where "Index = %_index%" get /Value
wmic path Win32_NetworkAdapterConfiguration where "Index = %_index%" get /Value
关于windows - 从 IPCONFIG/all 解析第二个 DNS,Windows 批处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41130434/