Mr. Script

Controlling Network Connections

Stepping outside of the box is a good thing.

I once saw a bumper sticker that read: I know everything. I just can’t remember it all at once. I like that phrase. It’s particularly descriptive of our lives as systems administrators. Ask us a question—any question—about how to perform a specific task in NT/Win2K/XP/9x and eight out of 10 times, we’ll have the correct answer right off the tops of our heads. For the remaining two times, we’ll know exactly where to find the answer. In other words, we know it, but we just can’t remember it.

Recently, I had a brief bout of “unremembering” when it came to a scripting question I received from Doug Lippi, a senior systems manager. Doug’s question was:

I’m trying to show a NIC’s state (connected/disconnected) and set its state (enabled/disabled) using the command line for Windows 2000. Is this possible? I’ve been unsuccessful.

My first thought was, of course, you can—by using Windows Management Instrumentation, as it can do everything but make coffee in the morning. I looked through the WMI object browser (just to refresh my memory, you understand) and sure enough, there it was. You can, indeed, use WMI to enumerate each NIC and display its state. But there was no corresponding method to change that state. This had to be wrong. How could it be that WMI—the all-seeing, all-powerful, supreme being of scripting—was unable to do something as fundamental as disabling a NIC? I couldn’t accept that, so I dug deeper. MSDN search…nothing. Deeper still. Google search…nothing!

Finally, I resigned myself to looking outside WMI. It was then that I remembered the Windows Shell object. It can be done! The Shell object can be used to enumerate the NICs, display their state, then enable or disable them—all from the command line.

<package>
<comment>
NICToggle.wsf

This script looks at your ‘Local Area Connection’
and enables it if disabled, disables it if enabled.
</comment>

<job>
<runtime>
<description>

Script for toggling network connection on/off
</description>

<example>

C:\>cscript ToggleNIC.wsf
</example>
</runtime>
<object id=”
objShell” progid=”Shell.Application”/>
<script language=”VBScript”>
‘Toggle NIC on or off
Option Explicit
Dim objCP, objEnable, objDisable, colNetwork
Dim clsConn, clsLANConn, clsVerb
Dim strNetConn, strConn, strEnable, strDisable
Dim bEnabled, bDisabled

strNetConn = “Network Connections”
strConn = “Local Area Connection”

strEnable = “En&able”
strDisable = “Disa&ble”

Set objCP = objShell.Namespace(3)
‘Control Panel

Set colNetwork = Nothing
For Each clsConn in objCP.Items
If clsConn.Name = strNetConn Then
Set colNetwork = clsConn.getfolder
Exit For
End If
Next

If colNetwork is Nothing Then
WScript.Echo “Network folder not found”
WScript.Quit
End If

Set clsLANConn = Nothing
For Each clsConn in colNetwork.Items

‘In case the LAN is named “connection 2”, etc.

If Instr(LCase(clsConn.name),LCase(strConn)) Then
Set clsLANConn = clsConn
Exit For
End If
Next

If clsLANConn is Nothing Then
WScript.Echo “Network Connection not found”
WScript.Quit
End If

bEnabled = True
Set objEnable = Nothing
Set objDisable = Nothing
For Each clsVerb in clsLANConn.verbs
If clsVerb.name = strEnable Then
Set objEnable = clsVerb
bEnabled = False
End If
If clsVerb.name = strDisable Then
Set objDisable = clsVerb
End If
Next

If bEnabled Then
objDisable.DoIt
Else
objEnable.DoIt
End If


‘Give the connection time to stop/start
WScript.Sleep 1000

</script>
</job>
</package>

Digging Into the Script
This script uses the Shell object to gain access to the Network Connections folder and, subsequently, the network connection itself. It then toggles the connection on and off by using “verb” methods to invoke actions from the menu. One caveat: Since it uses the Shell object, it relies on standard naming conventions. The Windows XP control panel item is called Network Connections. Win2K calls it Network and Dial-up Connections. The script doesn’t work at all on NT 4.0 or Win 9x, because the Network applet doesn’t use the same folder-based approach to managing connections. Moreover, the individual connection will often be appended with a number such as 2 or 3.

I’ve tried to compensate for this in the script by looking for Local Area Connection inside the connection name, rather than performing an exact match comparison. If you’re the sort of person who renames these things to, say, 3COM PCI NIC and/or LinkSys PCMCIA NIC, then you’ll have to change the script accordingly. You’ll also need to take care with multi-homed machines to ensure that you’re disabling the correct connection.

As a standalone script, it doesn’t do much. Let’s face it: Sometimes the GUI is better. If all we need to do is enable/disable a network connection, we can simply right-click the network connection in our Network Connections folder and click Enable or Disable. Indeed, that’s exactly what the script is doing from within the code. However, if you put this functionality into a larger script—one that might require disabling network access at a particular point in the script execution and then enabling it again at another point—its value increases dramatically.

The Network Is Down
As of this writing, the whole world is in the midst of recovering from the Blaster worm. What made this recovery difficult is that the worm would often cause your computer to reboot (randomly) before you could finish removing it. In order to complete the fix, you had to take your computer off the network, apply the fix, delete MSBlast.exe from your system32 folder, configure your Internet Connection Firewall, reconnect to the network, and download and apply the update to fix the port 135 vulnerability. Wouldn’t it be cool to put all of these steps into a script that you simply run on every workstation? Suddenly, being able to disable a network connection from script code becomes a real timesaver, doesn’t it?

Even though Doug wrote to me before the Blaster worm hit, he was almost precognitive in identifying a task for which administrators everywhere would need a solution. Of course, I suppose you could just go around and unplug everyone’s network cable, or simply power off the hub, but where’s the fun in that?

By engaging in a bit of outside-the-box thinking, you’re sure to find yourself using the code in this script quite often as part of a larger task. Now that you know how to do it, just make sure that you always remember it.

About the Author

Chris Brooke, MCSE, is a contributing editor for Redmond magazine and director of enterprise technology for ComponentSource. He specializes in development, integration services and network/Internet administration. Send questions or your favorite scripts to chrisb@componentsource.com.

comments powered by Disqus

Reader Comments:

Sun, Oct 17, 2010 TardisRepairMan

A great new tool in my scripting toolbox! I just used it to re-start the nic on my laptop while RDPing onto it. I cut and pasted the script into VBSEdit and used the search replace to get the right Quotes in as suggested. Then I used dim to dimension the objShell and put in the VBS set objShell=CreateObject("shell.application") near the start. Many Thanks!

Fri, Mar 19, 2010 patoc Colorado, USA

Redmond, WA must have heard you. Vista and later incorporate WMI method to disable.

Sun, May 3, 2009 Samuel Montoya Australia

Utterly fantastic. Thanks so much for your work and insights into scripting, you're right - very simple standalone but stupidly helpful in the context of larger scripts. I just wasted 2 days looking through WMI stuff and google results to finally stumble across this! Hello VPN management.

Wed, Feb 27, 2008 Rob Eberhardt Cincinnati, OH, USA

Too bad this depends on the UI, which has changed in Vista and so broken the script.

With a little help from Scriptomatic, I whipped up something similar *WITH* WMI. Hope it helps someone else:

OPTION EXPLICIT
'purpose: disable and re-enable any wlan adaptors on local system
'author: Rob Eberhardt

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20

DIM objWMIService, colItems
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)

DIM objItem
For Each objItem In colItems
IF objItem.NetConnectionID = "Wireless Network Connection" THEN
DIM strNetEnabled
IF objItem.NetEnabled THEN strNetEnabled = "Enabled" ELSE strNetEnabled = "Disabled"
call WScript.Echo(objItem.Name & " is " & strNetEnabled & ".")
call WScript.Echo("Disabling...")
call objItem.Disable()
call WScript.Echo("Enabling...")
call objItem.Enable()
END IF
Next

Mon, Dec 4, 2006 thor new zealand

Awesome: this code is excellent way to start exploring using the shell stuff as opposed to WMI, especially with the iteration of each of the objects. The disable method in win32_networkadapter is not available until vista. One could use this code here to find his way around the objects to discover what else is possible...

Mon, Nov 20, 2006 Anonymous Anonymous

Should have included logic for disconnecting wireless

Sat, Jul 22, 2006 marcus india

I will di further, thanks for giving me starting point. useful one.

Mon, May 29, 2006 Anonymous Anonymous

Great!!!

Sun, May 21, 2006 ashwin mumbai

Thanks for this script mate. I've been looking for this for a long time.

Wed, Feb 22, 2006 Anonymous Anonymous

It is just great.
I am looking for
enable/disable of wireless nic
from last 1 week. And today I got
this.

Wed, Feb 15, 2006 frank munich

cool, exactley what i was looking for

Thu, Jan 12, 2006 marius romania

Well, done that, but i'm still getting an error. On line 76 Microsoft VBScript runtime error: Object required. It's referring either to "objDisable.DoIt" or "objEnable.DoIt" . Can some one help me ?

Wed, Nov 30, 2005 Anonymous Anonymous

Thank you! Being trying to sovle this issue for long time.

Wed, Aug 17, 2005 Vaibhav Mumbai

pretty handy code

Wed, Jun 29, 2005 TEK Germany

Here the cleaned up and germanized version vor your conveniance.



NICToggle.wsf
This script looks at your ‘Local Area Connection’
and enables it if disabled, disables it if enabled.




Script for toggling network connection on/off



C:\>cscript ToggleNIC.wsf



set objShell=CreateObject("shell.application")

' Toggle NIC on or off
Option Explicit
Dim objCP, objEnable, objDisable, colNetwork
Dim clsConn, clsLANConn, clsVerb
Dim strNetConn, strConn, strEnable, strDisable
Dim bEnabled, bDisabled

Const NETWORK_CONNECTIONS = &H31&

strConn = "Local Area Connection"

'strEnable = "En&able"
strEnable = "&Aktivieren"
'strDisable = "Disa&ble"
strDisable = "&Deaktivieren"

Set colNetwork = Nothing
Set colNetwork = objShell.Namespace(NETWORK_CONNECTIONS) ' Network Connections (independent of country/language)

If colNetwork is Nothing Then
WScript.Echo "Network folder not found"
WScript.Quit
End If

Set clsLANConn = Nothing
For Each clsConn in colNetwork.Items
' In case the LAN is named “connection 2”, etc.

If Instr(LCase(clsConn.name),LCase(strConn)) Then
Set clsLANConn = clsConn
Exit For
End If
Next

' WScript.Echo clsLANConn

If clsLANConn is Nothing Then
WScript.Echo "Network Connection not found"
WScript.Quit
End If

bEnabled = True
Set objEnable = Nothing
Set objDisable = Nothing
For Each clsVerb in clsLANConn.verbs

' WScript.Echo clsVerb.name

If clsVerb.name = strEnable Then
Set objEnable = clsVerb
bEnabled = False
End If
If clsVerb.name = strDisable Then
Set objDisable = clsVerb
End If
Next

If bEnabled Then
objDisable.DoIt
WScript.Echo clsLANConn & " deaktiviert"
Else
objEnable.DoIt
WScript.Echo clsLANConn & " aktiviert"
End If

'Give the connection time to stop/start
WScript.Sleep 1000



Wed, Mar 30, 2005 moonface the far away tree

A step by step guide to getting this script working:

1. Create a text file in notepad and name it NICToggle.wsf

2. Copy and paste the code from this page, starting with and ending with to your text file.

3. The web publishing software has replaced all the single and double quotes with fancy opening and closing quote characters. These will cause errors in the script file. We will use the notepad Replace function from the Edit menu to replace them with normal quote characters

- Copy a fancy single quote from the code (there is one on line 19) to the find box of the dialog.
- Enter a normal single quote in the replace box.
- Click the replace all button.

- Copy a fancy opening double quote from the code (there is one on line 26) to the find box of the dialog.
- Enter a normal double quote in the replace box.
- Click the replace all button.

- Copy a fancy closing double quote from the code (there is one on line 26) to the find box of the dialog.
- Enter a normal double quote in the replace box.
- Click the replace all button.

4. Save your text file. You can run it from explorer with a double click or from the command line.

Thu, Mar 10, 2005 chris government

what is the best connection in internet specially the wireless connection?
what is the latest anti-virus you are using now?

Wed, Jul 21, 2004 obee Anonymous

Did anyone manage to get this script? please send me a copy obeekenobi@hotmail.com

Thu, Jun 10, 2004 Anonymous Anonymous

where's the script?

Sun, May 9, 2004 Anonymous Anonymous

Can someone please send me the script at alexts@ms.com?

Sun, May 9, 2004 Anonymous Anonymous

Please post the screept

Thu, Apr 22, 2004 Bananaman30 Anonymous

Hi guys!
could someone send the scripts to me at bananaman30@hotmail.com.

Thanks

Thu, Apr 15, 2004 Raul Washington D.C

Where is the script? Could someone email the script?

Mon, Mar 22, 2004 Meagain Arizona

Hello, I hope someone catches this post.. I am looking to do this and would like to have the source. Can someone please send me the link to it. Thanks!! email: meagain35@lycos.com

Thu, Mar 11, 2004 Anonymous Anonymous

Is the script available for download or do I have to type it out manually?

Mon, Feb 16, 2004 Anonymous Anonymous

The script is not availabel. Can someone repost the script?

Thu, Jan 8, 2004 Julian London, UK

I can't see the script!!!
Can anyone send it to me?

Cheers

Thu, Jan 8, 2004 Anonymous Anonymous

HOw can I download the SCRIPT !? $%$@$$E!~~~!!!!

Wed, Dec 24, 2003 Paul san diego

12-24-03, Where is the script?

Fri, Dec 12, 2003 f00_beerd Anonymous

should say the <object> tag. Wish it work in WMI and that we could use .item("Network Connections") instead of iteration, but at least it is possible. BTW - It also should be set objShell=WScript.CreateObject("shell.application") -Red

Fri, Dec 12, 2003 f00_beerd Anonymous

I stumbled upon this method the hard way (digging through the dialup.htt file). Using it to turn off wireless nic while in office and enable when offline or at user request. try:
set objShell=CreateObject("shell.application")
instead of the tag, works for me. Thx

Sat, Nov 22, 2003 Eric Phoenix

I get the same "is not valid: progid" on XP Professional. BS

Mon, Nov 10, 2003 Robert Anonymous

executing the above code on windows 2000 pro only results in the following error:
NICToggle.wsf(17, 24) Windows Script Host: The value for the attribute is not valid : progid

Sun, Nov 9, 2003 Anonymous Anonymous

Thanks! This script rocks. My XP runs much faster if I turn off my cable connection -this is handy to turn it on & off. cheers. mandar damle

Fri, Nov 7, 2003 Anonymous Anonymous

Was about to write one but this one works and saves me a few minutes. :-)

Wed, Nov 5, 2003 Anonymous Anonymous

I like I like...I'll probably be using this soon.

Mon, Nov 3, 2003 Anonymous Anonymous

This is very useful for Home user like me. My DSL connection (via router) will go to sleep mode after 10 min. of inactive and to start the connection I need to either rebbot the pc or I have to renew IP.

Chris Thanks and Keep it up....

Mon, Nov 3, 2003 Bruce Weatherford Austin, TX

This for this article! I have been looking for information on how to script the disabling of a NIC for over 6 months.

Wed, Oct 29, 2003 Mike Harvey St Louis Mo

Very good article

Add Your Comment Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Comment:
Please type the letters/numbers you see above

Redmond Tech Watch

Sign up for our newsletter.

I agree to this site's Privacy Policy.