Friday, April 27, 2012

How To Write A Windows Script To Change Network Settings On The Fly

How To Write A Windows Script To Change Network Settings On The Fly:
This 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, and also used to to automate Microsoft SyncToy 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.
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.



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.


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.

Checking my network card settings after running the script, I confirmed that the script did in fact make the static IP setting changes.



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.

After running this, I went into my adapter settings and sure enough, it was set back to Obtain an IP address automatically.



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




No comments:

Post a Comment

[Please do not advertise, or post irrelevant links. Thank you for your cooperation.]