Pinterest Stumbleupon Whatsapp
Ads by Google

change network settings scriptThis week, I stumbled across an interesting problem. In many offices or work environments, you might need to redefine your network settings to connect to different networks. For example, some people take their laptop home with them and have a static IP set up specifically for that machine. However, since the work network is usually DHCP, that requires the person to keep changing the network settings between a static IP or automatic DHCP depending where they are.

A more common problem is for engineers or IT staff that often need to connect to devices or machines on a small network within a building. To connect to that isolated network, you have to change your network settings to a static IP. Later, when you reconnect to the corporate network, it’s back to DHCP again.

I found myself in this situation often enough, and got so tired of browsing to the network card, opening up the IP settings and making those edits, that I decided it was high time to put together a VB script that would do it all in one or two clicks.  If you’ve followed along with my programming articles, then you know that I love VB scripts. I once used it to create a possessed computer Create A Freaky Possessed Computer With Windows Script For Halloween Create A Freaky Possessed Computer With Windows Script For Halloween There are a lot of fun pranks you can play on your friends with a computer. You've probably seen all of those creepy YouTube videos that people forward to each other for a good scare.... Read More , and also used to to automate Microsoft SyncToy How To Create A Data Backup Tool With SyncToy & VB Script How To Create A Data Backup Tool With SyncToy & VB Script We've covered a lot of backup solutions here at MUO, and all of these solutions are great, but if you're working in an environment that is wary about free 3rd party software packages, or companies... Read More for data backups.

It’s also possible to accomplish this task with VB script, and it’s even possible to make it flexible enough so that it can accept user input for the static IP address. In this article, I’ll show you how to do it in three sections.

Creating a Network Setting Change Script

There are three main tasks you need to accomplish with the script in order to create this little app for switching network settings. The first is to use the script to create static IP settings. The next is to come up with a script to enable DHCP. Finally, the last is to ask the user which task they want to do, and then use that feedback to accomplish it.

VB Script to Set Static IP Settings

Remember, the following scripts need to be saved as a text file with a .wsf extension in order to work on a Windows PC. The following script will change your network settings to a static IP with a specific subnet mask and default gatewall, with all three hard coded into the script.

Ads by Google

For all code samples listed in this article, make sure to add “<job><script language=”VBScript”>” at the beginning and “</script></job> at the end, otherwise the code won’t run.
Here’s the static IP change script:

Option Explicit

On Error Resume Next

Dim objWMIService
Dim objNetAdapter
Dim strComputer
Dim arrIPAddress
Dim arrSubnetMask
Dim arrGateway
Dim colNetAdapters
Dim errEnableStatic
Dim errGateways

strComputer = "."

arrIPAddress = Array("192.168.1.106")
arrSubnetMask = Array("255.255.255.0")
arrGateway = Array("192.168.1.1")

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")

For Each objNetAdapter in colNetAdapters
     errEnableStatic = objNetAdapter.EnableStatic(arrIPAddress, arrSubnetMask)
     If Not errEnableStatic = 0 Then
     	WScript.Echo "Failure assigning IP/Subnet."
     End If

     errGateways = objNetAdapter.SetGateways(arrGateway)
     If Not errGateways = 0 Then
     	WScript.Echo "Failure assigning Gateway."
     End If

Next
WScript.Quit

This script uses the Windows WMI service in Windows to accomplish the goal of changing settings. You can see the three fixed array variables loaded with the IP addresses, and then where the script checks for the active “enabled” network card. Then it uses the “EnableStatic” and “SetGateways” methods to make those required changes. When I run the script on my home network (where I require DHCP), you can see where the script successfully changed my adapter settings, and I’ve lost my Internet connection.

Having proved that the static-IP part of the script works, it’s time to write the script that will set the adapter to DHCP so it’ll automatically detect the network IP. Here’s the script that you can use to do that.

Option Explicit

On Error Resume Next

Dim objWMIService
Dim objNetAdapter
Dim strComputer
Dim errEnable

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")

For Each objNetAdapter in colNetAdapters
     errEnable = objNetAdapter.EnableDHCP()
Next

WScript.Quit

As you can see, this script is a lot simpler. It also uses WMI, but the only function required is “EnableDHCP”. This is performed on the currently enabled network adapter. After saving and running this script, my adapter card settings changed back to DHCP, and my Internet connection was working again.
change network settings script
So, now that you’ve got the code to perform both of the important actions, the next part of this trick will be to take input from the user to determine exactly what static IP they want. To re-enable DHCP, you can require the user to enter the word “AUTO” for automatically detect the IP.
Here’s what this new, full script incorporating the two scripts above looks like.

Option Explicit

On Error Resume Next

Dim objWMIService
Dim objNetAdapter
Dim strComputer
Dim arrIPAddress
Dim arrSubnetMask
Dim arrGateway
Dim colNetAdapters
Dim errEnableStatic
Dim errGateways
Dim strInput
Dim errFailed

errFailed = 0

strInput = InputBox("Type Static IP Address or AUTO")

If strInput = "AUTO" Then

	strComputer = "."
	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
	Set colNetAdapters = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")

	For Each objNetAdapter in colNetAdapters
	     errEnable = objNetAdapter.EnableDHCP()
	     If Not errEnable = 0 Then
	     	WScript.Echo "Setting DHCP Failed."
		errFailed = 1
	     End If
	Next
Else
	strComputer = "."
	arrIPAddress = Array(strInput)
	arrSubnetMask = Array("255.255.255.0")
	arrGateway = Array("192.168.1.1")

	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
	Set colNetAdapters = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")

	For Each objNetAdapter in colNetAdapters
	     errEnableStatic = objNetAdapter.EnableStatic(arrIPAddress, arrSubnetMask)
	     If Not errEnableStatic = 0 Then
	     	WScript.Echo "Failure assigning IP/Subnet."
		errFailed = 1
	     End If

	     errGateways = objNetAdapter.SetGateways(arrGateway)
	     If Not errGateways = 0 Then
	     	WScript.Echo "Failure assigning Gateway."
		errFailed = 1
	     End If

	Next

End If

If errFailed = 0 Then

	WScript.Echo "IP Settings Successfully Modified."

End If

WScript.Quit

This script uses the InputBox function to get either the static IP or the “AUTO” command from the user.
change network settings script

If anything other than “AUTO” is typed into the field, that will be used as the static IP string in the section of code that uses WMI to set the static IP settings for the network adapter. There’s also a check for the “0” confirmation saying everything went okay.

script to change network settings

Checking my network card settings after running the script, I confirmed that the script did in fact make the static IP setting changes.
script to change network settings
Now to test the AUTO script. Typing AUTO satisfies the first condition in the “IF” statement checking for AUTO. This runs the alternate script that enables DHCP.

script to change network settings

After running this, I went into my adapter settings and sure enough, it was set back to Obtain an IP address automatically.
script to change network
While it may be a simple enough task to go into your network card settings and change to static or DHCP, if you have to do it really often it can become a real pain. You could do it from a command line using “netsh”, but again, you need to remember the command syntax.

Using the script above allows you to build a quick and easy utility that you can use anytime to switch your network settings on the fly.

Think you might give this Windows Script a try? Any other ideas to tweak it and make it even better? Share your thoughts and suggestions in the comments section below.

Image Credit:Binary Codes via Shutterstock

  1. Jomar
    September 22, 2016 at 8:25 pm

    I was wondering about this, in my workplace a script like this would be the difference between spending a day working with multiple computers or just a few hours, only thing is that I'm not too fluent in this type of scripting so my question is this, if I told you what I needed the script to do, could you point me to the right direction of how I could learn to use this?

  2. John
    June 19, 2016 at 1:59 pm

    I have a question, I have a Win 10 system that upon entering any IP address or AUTO into the input field, It returns with an error window titled "Windows script host" with an error message of "failure assigning IP/subnet" & "failure assigning gateway" both repeating two times.

    I know this is close but I am not sure what I am missing.

    • Ryan Dube
      June 19, 2016 at 2:48 pm

      Hi John. It sounds like it could be an issue with security settings, possibly. That user may not have permissions to make changes to the IP settings. You might want to check if the Windows User Account Control is turned on or not, and if it is, how strict are the security settings? That would be the first place I would look. Good luck!

  3. man17018
    April 28, 2016 at 10:41 pm

    This is really helpful, but from a "limited User" account, I have to add a step at the beginning to access the IPv4 Properties by way of the Local Admin + PW in order to effect the desired changes. How do I do this automatically, without jumping through so many hoops?

    I do have local admin access, off network, so that I'm able to work on PLCs and WiFi servers that I'm configuring in the field, but it's annoying to have to constantly reset the IPv4 properties whenever I reconnect to the network at the office. Any thoughts?

  4. TruMacMind
    April 24, 2016 at 7:24 am

    Is it possible to write this in bash? I would love to test this in my environment.

  5. redhotborscht
    February 21, 2016 at 7:54 am

    For anyone interested in setting static IPs with DNS, try the following batch. (You might need to replace "Local Area Connection" with whichever adapter name you see in Control Panel\Network and Internet\Network Connections, i.e. "Local Area Connection 2" or "Wireless Network Connection".) Save this as a .bat file.

    @ECHO OFF

    netsh interface ipv4 add address name="Local Area Connection" address=192.168.1.2 mask=255.255.255.0 gateway=192.168.1.1

    netsh dnsclient add dnsservers name="Local Area Connection" address=1.1.1.1 index=1 validate=no

    netsh dnsclient add dnsservers name="Local Area Connection" address=2.2.2.2 index=2 validate=no

    PAUSE
    .

  6. Geno
    January 13, 2016 at 2:05 am

    Same problem as Tester.

  7. JoeMoe
    December 9, 2015 at 6:45 pm

    I realize this article is 3 years old; however, it's still somewhat relevant, since windows 7 is still very prevalent and the new PowerShell commands don't work well yet.

    My question is this: I need to script a change in DNS settings for a bunch of computers. This script could be very helpful. However, it, and every other VB script I've found online, has one big problem: It loops through EVERY SINGLE INTERFACE and attempts to make the change!! This will not work! I have machines which are purposefully set to other networks; not count iSCSI adapters, bluetooth, and such.

    I can request that the author provide a simple 'if', but I will go work on it myself also to see if I can come up with the solution myself.

  8. Tester
    October 21, 2012 at 10:48 am

    I have problems with these instructions on windows 7 computer. I create a file with the extension add the jscript commands to the beginning and end of the script you placed in the coding box above and then attempt to run.

    It says error Line 1, Char 15. Error 80040049
    Has something to do with the adding of the
    section

  9. venkatp16
    June 22, 2012 at 2:05 am

    netsh or any other handy tools will be more useful

  10. Murgichoor
    April 28, 2012 at 1:20 pm

    How about DNS entry for the last script with auto?

    • Ryan Dube
      May 3, 2012 at 11:38 pm

      Hey Murgichoor - maybe this code that I found online would help:

      "For Each objNetAdapter in colNetAdapters
      arrDNSServers = Array(sDNS1, sDNS2)
      objNetAdapter.SetDNSServerSearchOrder(arrDNSServers)
      Next"

      sDNS1 and sDNS2 are the two strings holding the two DNS Servers

      • Murgichoor
        May 4, 2012 at 5:25 am

        Thank you for the response Ryan, But I am unable to incorporate it altogether, it keeps on giving me errors. I am sure you can guess scripting is not one of my strong suit. :) Cheers

      • tchill2
        September 6, 2012 at 1:34 pm

        Has anyone been able to incorporate the DNS code?

  11. Pablo
    April 28, 2012 at 1:16 pm

    Great trick. Very Useful and well explained.
    Thanks!!!

  12. Kaggy
    April 27, 2012 at 6:22 pm

    Can probably use netsh commands like
    netsh interface ipv4 set address

    For DHCP
    sc stop dhcp
    sc config "dhcp" start= disabled

    Would probably work, thou i didn't test.

    • epiquestions
      April 28, 2012 at 8:14 am

      then why don't you test it first before you comment?

Leave a Reply

Your email address will not be published. Required fields are marked *