Search code examples
batch-filefind

How to find next line in batch file?


I use this code to show my Preferred DNS server:

for /f "tokens=1-2 delims=:" %%a in ('ipconfig/all^|find "DNS Servers"') do set DNS1=%%b
set DNS1=%DNS1:~1%
echo DNS1 is:
echo %DNS1%

now i want to show my Alternate DNS server, how can do it? i can't find the next line enter image description here


Solution

  • This is a bit ugly in Batch. Basically you look for a start string ("DNS-Server"), set a flag until you find an endstring (a line not starting with four spaces) where you unset the flag.

    @echo off
    setlocal enabledelayedexpansion
    
    set "flag=0"
    set "DNS=0"
    
    for /F "delims=" %%I in ('ipconfig /all') do ( 
      echo %%I|findstr /c:"  DNS-Server" >nul && (
        set /a DNS+=1
        set "flag=true"
        set "Line=%%I" 
        set "DNSServ[!DNS!]=!line:*: =!"
      ) || (
        if defined flag (
          echo %%I|findstr /bc:"    " >nul && (
            for /f "tokens=*" %%J in ("%%I") do (
              set /a DNS+=1
              set "DNSServ[!DNS!]=%%J"
            )
          ) || set "flag=" 
        )
      )
    )
    set DNSServ[
    

    NOTES:

    • this is build in German, ipconfig is language dependent - you probably need to adapt the search string.
    • this is built for a system with just one (active) NIC. If there is more than one, you get all the DNS-Servers for all NICs (probably - can't test now) without distinction which server belongs to which NIC.