Sunday, March 1, 2015

Set DNS with just double click with Batch file

Sometimes we need to change our DNS address manually to gear up browsing speed. To do so with just a double click I have created a batch file. You have to just double click and type you preferred and alternate DNS server addresses. It will update the DNS to all connected network, so you need to connect to network first (It will not update DNS to disconnected interface).
Copy the below text and paste it to Notepad and Save as with *.bat extension e.g. SetDNS.bat or Download the file that I already have created: SetDNS.bat


@ECHO off
:: BatchGotAdmin
:inputDNS
REM Check for permissions
>NUL 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM If error is flag set, It doesn't have Admin privileges.
IF '%errorlevel%' NEQ '0' (
    ECHO Requesting administrative privileges...
    GOTO UACPrompt
) ELSE ( GOTO gotAdmin )

:UACPrompt
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    SET params = %*:"=""
    ECHO UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    DEL "%temp%\getadmin.vbs"
    EXIT /B

:gotAdmin
    PUSHD "%CD%"
    CD /D "%~dp0"

:inputDNS
ECHO -----------------------------------SetDNS-----------------------------------
ECHO Please Input DNS Server Address in correct format and hit Enter.
ECHO If you get "Element not found." message, it seems you did not put in correct format. And you need to try again.
ECHO Leave blank and hit enter to use default DNS servers.
ECHO -------------------------- Correct Format: X.X.X.X -------------------------
SET /P _dns1=Please input Primary DNS Server (default:8.8.8.8): || Set _dns1=8.8.8.8
SET /P _dns2=Please input Alternate DNS Server (default:4.2.2.1): || Set _dns2=4.2.2.1
GOTO :SetDNS
EXIT /B

:SetDNS
REM Gathering all installed network adapters from the list.
FOR /F "skip=2 tokens=4*" %%a IN ('NetSh Interface IPv4 Show Interfaces') DO (
    CALL :UseNetworkAdapter %%a "%%b"
)

GOTO :FlushDNS
EXIT /B

:UseNetworkAdapter
REM %1 = State, %2 = "Adapter Name" (quoted) and %~2 = Adapter Name (unquoted)

SET _interfacename=%~2
SET _shortintfn=%_interfacename:~0,4%
REM Applying settings except Loopback Pseudo-Interface
IF NOT %_shortintfn%==Loop    (   
    IF %1==connected (
        ECHO Setting up Primary DNS server of %2 to %_dns1%
        netsh interface ip set dns name=%2 static %_dns1%
        ECHO Setting up Alternate DNS servers of %2 to %_dns2%
        netsh interface ip add dns name=%2 %_dns2% index=2
        ECHO DNS Servers update successfully...
    )
)
EXIT /B

:FlushDNS
ECHO ----------------------------Windows DNS Flush-------------------------------
ipconfig /flushdns
ECHO ----------------------------------------------------------------------------
ECHO Please re-connect your network if you still face any problem.
PAUSE ECHO Press Any Key to exit...
EXIT /B