1 script to switch to and from static IP or DHCP

FAST380 picture FAST380 · Nov 12, 2014 · Viewed 10k times · Source

Is there a way to have 1 script that checks current IP settings (DHCP or Static), and then alternates to the other.

Currently I have one script to set DHCP, and another to set IP. I would like one script that looks at the current settings, and then switches to the other. In a perfect world it would have a pause telling the user which direction it is being switched.

These are what I am using so far.

Scrip 1

@echo Be sure Network Cable is unplugged and

@pause

netsh int ipv4 set address name="Local Area Connection" source=static address=10.38.xxx.xxx mask=255.255.255.xxx gateway=10.38.xxx.xx

netsh int ipv4 set dns name="Local Area Connection" source=static address=10.99.xx.xx register=primary validate=no

Script 2

netsh interface ipv4 set address name="Local Area Connection" source=dhcp

netsh interface ipv4 set dnsservers name="Local Area Connection" source=dhcp

@echo It may take a few moments for changes to take effect. You may close this window or
@pause

Thank you very much for your help.

Answer

MC ND picture MC ND · Nov 13, 2014
@echo off
    setlocal enableextensions disabledelayedexpansion

    set "name=Local Area Connection"

    echo Be sure Network Cable is unplugged and
    pause

    netsh interface ipv4 show addresses "%name%" | findstr /r /i /c:"DHCP.*No$" >nul 2>nul 

    if errorlevel 1 (

        echo DHCP mode - Press any key to change to static IP
        pause >nul 
        netsh int ipv4 set address name="%name%" source=static address=10.38.xxx.xxx  mask=255.255.255.xxx  gateway=10.38.xxx.xx
        netsh int ipv4 set dns     name="%name%" source=static address=10.99.xx.xx    register=primary      validate=no

    ) else (

        echo Static mode - Press any key to change to DHCP
        pause >nul 
        netsh interface ipv4 set address    name="%name%" source=dhcp
        netsh interface ipv4 set dnsservers name="%name%" source=dhcp
    )

    echo It may take a few moments for changes to take effect. You may close this window or
    pause

At this moment i can not test it, but... Check the current state (code searchs for DHCP .... No) and switch to the other