Board logo

标题: [网络连接] WIN10怎么用批处理获取主DNS和备用DNS? [打印本页]

作者: nssb123    时间: 2018-5-3 08:08     标题: WIN10怎么用批处理获取主DNS和备用DNS?

  1. @echo off
  2. setlocal enabledelayedexpansion
  3. set command=" ipconfig /all | findstr /c:"DNS Servers" /rc:"[ ][ ][ ]*[0-9]" "
  4. for /f "tokens=1,2,*" %%a in (' %command% ') do (
  5. if "%%b"=="" (
  6. set DNS_Servers2=%%a
  7. ) else (
  8. set value=%%c
  9. set value=!value:*:=!
  10. set %%a_%%~nb=!value:* =!
  11. )
  12. )
  13. echo 首选 DNS:%DNS_Servers%
  14. echo 备用 DNS:%DNS_Servers2%
  15. pause
复制代码
百度搜到的这个最后只能显示备用DNS,,,,首选DNS不会显示。。。。
作者: Batcher    时间: 2018-5-3 09:26

执行这个命令 ipconfig /all > a.txt
把 a.txt 压缩上传
我试试
作者: yhcfsr    时间: 2018-5-3 10:24

本帖最后由 yhcfsr 于 2018-5-3 10:28 编辑
  1. @echo off
  2. set commamd="netsh interface ip show dnsservers|findstr "[0-9]*\.[0-9]*\.""
  3. for /f "delims=" %%a in ('%commamd%') do (
  4. if not defined DNS1 ( SET "DNS1=%%a" ) else ( set "DNS2=%%a" )
  5. )
  6. SET "DNS1=%DNS1: =%"&SET "DNS2=%DNS2: =%"
  7. echo;首选DNS:%DNS1:*:=%
  8. echo;备用DNS:%DNS2:*:=%
  9. pause
复制代码
又或者显示IP和DNS
  1. @echo off
  2. ipconfig /all|findstr "[0-9]*\.[0-9]*\."
  3. pause
复制代码

作者: WHY    时间: 2018-5-3 11:40

  1. set command=" ipconfig /all | findstr /i /b /r /c:" *DNS Servers" /c:" *DNS 服务器" /c:" *[0-9]" "
  2. for /f "tokens=1* delims=:" %%a in ('%command%') do (
  3.     if "%%b" == "" (set 备用=%%a) else (set 首选=%%b)
  4. )
  5. echo;%首选: =%
  6. echo;%备用: =%
  7. pause
复制代码

作者: nssb123    时间: 2018-5-3 17:36

[attach]11201[/attach]回复 2# Batcher
作者: nssb123    时间: 2018-5-3 17:41

这个首选DNS会变成IPV6地址。回复 4# WHY
作者: nssb123    时间: 2018-5-3 17:43

回复 3# yhcfsr


    感谢,试过很好用。。。。。
作者: WHY    时间: 2018-5-3 20:03

回复 6# nssb123


    这样好了
  1. @echo off
  2. PowerShell "[string](ipconfig /all) -match '(?<=DNS 服务器)(?!DNS 服务器).*?((?:\d+\.){3}\d+) *((?:\d+\.){3}\d+)'|%%{$matches[1],$matches[2]}"
  3. pause
复制代码

作者: nssb123    时间: 2018-5-3 20:45

回复 8# WHY


    谢谢,但是我试了下在CMD里运行这个和powershell里运行这个都会显示错误,,我已经用3楼的代码实现了,感谢。。。
作者: Batcher    时间: 2019-6-4 13:42

  1. @echo off
  2. for /f "delims=" %%i in ('netsh interface ip show dnsservers ^| findstr "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*"') do (
  3. if not defined DNS1 (
  4.         set "DNS1=%%i"
  5.     ) else (
  6.         set "DNS2=%%i"
  7.         goto :OutPut
  8.     )
  9. )
  10. :OutPut
  11. set "DNS1=%DNS1: =%"
  12. set "DNS2=%DNS2: =%"
  13. echo %DNS1:*:=%
  14. echo %DNS2:*:=%
  15. pause
复制代码

作者: Batcher    时间: 2019-6-4 13:54

回复 3# yhcfsr


我公司的电脑同时设置了有线和无线的主DNS、备DNS
结果获取到的是有线的主DNS和无线的备DNS
作者: xftvwuchao    时间: 2022-8-13 10:10

本帖最后由 xftvwuchao 于 2022-8-13 10:12 编辑

回复 8# WHY

PowerShell "[string](ipconfig /all) -match '(?<=DNS 服务器).*?((?:\d+\.){3}\d+) *((?:\d+\.){3}\d+)'|%%{$matches[1]}"
PowerShell "[string](ipconfig /all) -match '(?!DNS 服务器).*?((?:\d+\.){3}\d+) *((?:\d+\.){3}\d+)'|%%{$matches[2]}"

首选DNS:223.6.6.6
备用DNS:223.6.6.6

我把它分成两行了

怎么让结果这样显示  大神




欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2