我正在尝试使用Windows批处理脚本将活动网关IP转换为变量。只能使用原生工具。
因此我使用命令'route'。打印输出的示例如下:
route print -4 0.*
===========================================================================
Interface List
4...2e 33 7a f5 ff e9 ......Microsoft Wi-Fi Direct Virtual Adapter
3...8c ae 4c ee 07 84 ......ASIX AX88179 USB 3.0 to Gigabit Ethernet Adapter #2
14...00 50 56 c0 00 01 ......VMware Virtual Ethernet Adapter for VMnet1
5...00 50 56 c0 00 08 ......VMware Virtual Ethernet Adapter for VMnet8
11...00 ff a7 b1 54 e7 ......TAP-Windows Adapter V9
12...2c 33 7a f5 ff e9 ......Dell Wireless 1560 802.11ac
1...........................Software Loopback Interface 1
13...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
2...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
15...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #3
===========================================================================
IPv4 Route Table
===========================================================================
Active Routes:
Network Destination Netmask Gateway Interface Metric
0.0.0.0 0.0.0.0 192.168.55.254 192.168.55.53 10
===========================================================================
Persistent Routes:
Network Address Netmask Gateway Address Metric
0.0.0.0 0.0.0.0 192.168.111.111 1
===========================================================================
如您所见,我有一条活动路线和持续路线。两者都有一个网关地址。
我只想将Active Gateway IP作为变量。
到目前为止,我已经创建了这个命令:
for /f "tokens=3" %%a in ('route -4 print 0.* ^| find "0."') do set "_active_gateway_address=%%a"
不幸的是,这导致持久网关(192.168.111.111)被捕获为变量,因为它是找到的最后一个条目。
如何在找到第一个匹配项时仅捕获活动网关(192.168.55.254)或使'find'停止?
非常感谢
答案 0 :(得分:1)
选项1 - 使用变量作为标志只读取第一个值
set "_active_gateway_address="
for /f "tokens=3" %%a in ('
route -4 print 0.* ^| find "0."
') do if not defined _active_gateway_address set "_active_gateway_address=%%a"
或使用goto
命令
for /f "tokens=3" %%a in ('
route -4 print 0.* ^| find "0."
') do set "_active_gateway_address=%%a" & goto :done
:done
选项2 - 检查第五个令牌存在
for /f "tokens=3,5" %%a in ('
route -4 print 0.* ^| find "0."
') do if not "%%b"=="" set "_active_gateway_address=%%a"