Got a question from Enrico,
“Good morning Steve, and Happy New Year!…I would like that when the user has a wired NIC up and running, the wireless NIC is automatically disabled, and as soon as the wired NIC disconnects, the wireless NIC activates.
This prevents the user to have both NICs up and running at the same time and above all prevents wireless access points to collapse for too many unneeded simultaneous connections.”
Awesome question Enrico.
There are other reasons for wanting this too. If you have both connections running, things like file transfers, or anything that needs the extra speed of Ethernet…might end up going through the wireless instead.
For this question, I have created a VB Script that will receive the names of the two network cards in its command line parameters.
For example, if you look at your network connections:
See the descriptions for them? That is what you will use to identify them.
If you wanted to watch the “Local Area Connection” adapter…and then switch the “Wireless Connection” Adapter, you would call the script like this:
The program will not display anything, but run in the background looking for the change. It will continue to run until the user logs out.
If the Local Area Connection is no longer connected, it will automatically enable the Wireless connection.
The reverse is true…if Local Area Connection becomes available, it will automatically disable the wireless connection.
The best place to run the script would be from a group policy computer configuration logon script (Not a user configuration) because it will run as local system and have the proper permission to enable and disable network cards.
You can get the script from here:
For 2003, Vista, Windows 7, and 2008:
NetSwitch.dat
For Windows XP:
Just rename to NetSwitch.vbs after downloading.
One more thing…Subscribe to my newsletter and get 11 free network administrator tools, plus a 30 page user guide so you can get the most out of them. Click Here to get your free tools
{ 50 comments… read them below or add one }
Nice script steve. Actually I have been looking for a way to disable a network card from vbscipt…just cut and paste part of your code to do what I need.
Thanks again đ
The wise answer (for Windows 7) would be to use task scheduler events “On event”.
Excellent idea RaFi. You are correct. This would work much better with stand alone machines.
Hi Steve. Just want to let some of your readers know that some laptops have this functionality built into the BIOS. Just take a look before deploying the script. It works really well.
Thanks for the tip Mike. Just got an email from Doug…and he says their HP laptops have this too….and on their dell laptops, there is an option in the driver to do this.
Our IBM machines have ThinkAdvantage which does the automatic switching which we have installed in the image. Works ok in our enviroment, I might look into the VBS script as well as the on event command.
Thanks for this guys.
Hey steve, I tried it in Windows XP, and I am getting a VB Script error. Any idea what I am doing wrong?
Hi John,
It looks like Windows XP does not have the enable/disable methods. I have found a work around that traverses the Network Connections folder, and performs a verb action on the interface.
One thing to look out for – if you have a different language version of XP, make sure you edit the NetSwitchXP.vbs file to reflect the name of “Network Connections”
I have updated the article to have a link to XP compatible version.
Thanks for the updated script steve. Actually I have been trying to do this for quite some time on XP. The problems I always came up against:
-Enable / Disable did not work under vb-script
-NETSH is broken for enabling and disabling network cards (It gives you an error that the default network connection cannot be disabled!)
You script solves this by using the folder access methods in vb-script. Brilliant!
Thanks for the script steve, I really appreciate you posting this one.
Glad it helped you out đ
This is a fantastic script steve. We already have put this on 10 of our laptops today. Works like a charm, and saves us from lots of headaches!
Glad to hear it Dave.
Thanks for the script steve. Works like a charm
Hi, we are trying to do a roll-out of this script by using the registry run (wscript //b C:\wireless\NetSwitch.vbs “local area connection” “wireless network connection”)
Unfortunately it doesn’t work. We are guessing that windows 7 does not run in with administrative rights.
Has someone else tried to implement it on several computers by an automatical startup? (task scheduler does not work for us. We cannot set the entry by GPO).
Thanks.
Hello Mike,
Those two methods are the only way I think it can run without any extra software. It can’t run in the context of the user, since by default all the scripts are run in a limited account (non uac) and therefore they cannot disable or enable the network card.
A way around it is to use this ‘runas’ program:
http://robotronic.de/runasspcEn.html
It allows you to run a program as an admin from the command line…but I believe you do need to encode a package with your username and password in it.
Hello Mike, works perfect in Wondows 7, but in windows xp i am getting the error line 65, character 2, an object ‘sAction is required’, code 800A01A8, running as local administrator
Windows xp SP3 Spanish
Thanks
Pablo, make sure you have both connections enabled before you run the script and it should work. I had the same problem as long as my wireless is disabled and I attempt to run the script I get the error.
I have a problem getting the script to work.
Both networks wired and wireless is running.
It is a danish Windows XP SP3 version.
Network folder name is “NetvĂŠrksforbindelser” and LAN name is “LAN-forbindelse” wireless name is “TrĂ„dlĂžs netvĂŠrksforbindelse”.
i am getting the error line 65, character 3, an object is obligated:âsAction is requiredâ, code 800A01A8, running comandpromt as local administrator
I have change the folder name in the script to “NetvĂŠrksforbindelser” so what am i doing wrong?
Best regards
Martin
Hi,
I have tried your script.
Unfortunately, every time I launch it, I have an error on my XP box. “Could not find network folder”.
At the beginning of the script, I have modified the sNetconn = “Connexions rĂ©seau” (french version of XP), but the problem remains.
“Connexions rĂ©seau” is the name displayed in the control panel.
Am I misunderstanding something ?
Thanks
Sorry, you can forget the last message !
Now I have another error (ligne65,car 3) : Object required : ‘sAction’.
I have modified the sEnable and sDisable but with no success.
Do I have to modify them, if Yes, with which value (as I am not sure to understand what is the sLanConn.verbs).
Thank you
OK last post about that !
So, I had to change the sEnable and sDisable to &Activer and &DĂ©sactiver.
Now, a bigger problem. There is an easy way to bypass(crash) the script :-/
Indeed, if you unplugged the ethernet card, then wait for few seconds and plug it again.
Wait for the message “reading ip address …” on the state tab of the ethernet card.
When you see this message, wait 1 sec and unplugged again the wire from the ethernet card.
The script will stop with an error like above : (ligne65,car 3) : Object required : âsActionâ.
Hope this helps
Hi Steve,
I am interested in running this on our company laptop but don’t have much experience with vbscript. Can you please provide an explanation of parts in script.
Hi Tanz,
Which parts are giving you trouble?
Hi Steve,
Script is working fine but when logging off the wireless card is still disabled if a wired conenction is present.
Upon logging back on the script runs and a runtime error occurs as the wireless is still disabled.
If you enable the wireless before logging off and then back on it works fine.
Can you advise on a fix for the VBS script to re-enable the wireless card either when logging in or logging off.
Many Thanks
XP being used
Hi Steve,
Script is great thanks.
If the wireless is connected on logon and there is no LAN connection I get a script error as it is looking for the LAN to be live.
So I need the script to be able to do the following on login:
1. If wireless connected and no LAN connection disable the LAN.
2. If LAN connected disable wireless
Hi Gary,
What error are you getting exactly?
Thanks,
Steve
For Windows 7 machines where users are not necessarily administrators try Accessityâs 1NET http://www.accessity.com.au/1Net.htm
On my Windows 7 x64 machine, this script seems to cause about 10-15% CPU usage from WmiPrvSE.exe (Windows Management Instrumentation). Do you know of anyway to get this vbs to run in a low priority mode or know of a way to prevent this from being so resource intensive?
One way to do this would be to increase the sleep time.
See the line:
WScript.Sleep(1000)
Change it to say:
WScript.Sleep(5000)
This may help…but will make it take longer to automatically switch.
Thanks for the tip Steve. That did the trick and the WmiPrvSE.exe isn’t consuming unnecessary resources like it did anymore. I went with 25000 for 25000 milliseconds (or 25 seconds) before initiating the automatic switch.
Do you know if this script could be used to Stop/Start the ‘WLAN AutoConfig’ service instead of Enabling/Disabling the network connections?
I think that would be helpful because then you don’t have to worry about your network connections having the specific name of ‘Local Area Connection’ and ‘Wireless Network Connection’.
Awesome script Steve! the Win7 version works flawlessly for me but I am having some issues with the Windows XP version. When I run the XP version without a connected LAN (both LAN and WLAN are enabled) it returns the error:
Script: C:\NetSwitchXP.vbs
Line: 65
Char: 3
Error: Object required: ‘sAction’
Code: 800A01A8
Source: Microsoft VBScript runtime error
I am able to run the script correctly as long as both LAN and WLAN are enabled and the LAN is connected when the script starts. To help with the scenario I have setup the script to copy locally to the client computers through GPO and created registry entries to run the script at startup. So it is possible they won’t have an active network connection when the script runs which will return the error stated above.
Thanks Steve! This works great. The only thing I can’t figure out is how to maintain the policy. Currently I log in as an administrator, and it works great. I unplug LAN and it switches and vice versa. When I restart or log off the machine, it doesn’t seem to keep the policy. Does this have to be done in a group policy? Thanks!
You would need to put the script so it runs each time you login…otherwise it is not running in the background to switch the cards
Group policy would work. Make sure the script runs under the user policy and not the computer policy
Steve
excellent. Again, thank you for this tool, and thank you for the quick response.
Hi Steve;
Thanks so much for the script. It works great! I am however trying to run this script through GPO. I have 2003 Server with Windows 7 laptops. The script runs beautifully locally, but doesn’t work through a GPO so well. Any ideas?
One thing to look out for…is the script running as a computer based logon script…or a user based one? It needs to be user to work.
Let me know either way.
Steve
Hi Steve
thank you for writing this script to disable wireless when ethernet is enabled, i am having problem similar to the one mentioned by John R, about object required for sAction (verb action) can you please send me your updated VB script file as i am trying to get this working on windows xp (English Language) and is not working
wadebot August 2, 2012:
On my Windows 7 x64 machine, this script seems to cause about 10-15% CPU usage from WmiPrvSE.exe
>>>
I have same problem, so I cannot suggest to just run this script. I modified script (changed WScript.Sleep(5000) to WScript.Quit – so it runs only once) and created Task by Event (source=e1cexpress in System Log).
I also wrote lan names in script.
Now it works fast and fine and not takes CPU all the time, only when i connect or diconnect cable.
Very nice script!
@echo off
start C:\netswitch.vbs “Local Area Connection” “wireless connection”
Can’t seem to run the script. I’ve put the script in the root of C:\ and try to run in cmd line. C:\netswitch.vbs, but I get the administrator prompt and then window pop ups for the description of the script, but the command does not run. Please help.
I can make the script run with elevated priviledges, but not with just regular user.
Thanks a ton for these scripts! It’s exactly what we’re looking for, works like a champ once I found your reply about making sure both nics are enabled when launching the script.
Only down side I can see is if someone has a user ‘smart enough’ to rename either of the network connection ‘names’ on their computer.
Hello!
-Thanks for the script! It is great.
How do I turn it off without restart?
-If someone wants to autostart, put it between scheduled tasks, with highest admin rights.
On http://www.bluemoonpcrepair.com/wp/?cat=51 this script was used as a template and code was added to read LAN and WLAN connections. Credits to http://www.bluemoonpcrepair.com and http://www.intelliadmin.com!!
At first i also had some issues which was mentioned in some posts here, but fixed that.
I’ve tested this script on XP, W7-x64 and W8-x64 systems. On XP this script isn’t working if the Windows install language isn’t English (also mentioned at sites where Joe Grossi published the original script). Because we want to use this script at several countries i’ve added some additinal languages so it must work now for NL,EN,DE,SE Windows installations.
On W8 the script wasn’t working but I also made it W8 compatible (in W8 there is no DefaultNameIndex regkey so i removed the check on this key (line starts with “If Not IsNull(DNIValue)….”) and it works :-). Also added logtofile entries (credits go to NateRice.com for the loggingcode).
While testing i had some situations that the wlan-adapter wasn’t disabled WHILE lan-connection was active, this could happen (as i can remember it correct) if the wlan-switch on the computer itself (the physical switch) is switched-off computer turned on with LAN-connected then wlan-adapter wil not be switched off because there is no WLAN-connection active. After switched-on the physical wlan-switch there is a wlan-connection and a lan-connection – not good.
So i added also a check of the wlan-connection every sleep-cycle.
I also wanted to prevent memoryleaks so added several object resets (e.g. Set colItems=Nothing) and changed some WMI-filter to make item-loops smaller/faster.
Here the editted script:
‘==========================================================================
‘ NAME: WirelessDisableOnLan.vbs
‘ AUTHOR : Joe Grossi, FMCNA
‘ DATE : 11/06/2012
‘ COMMENT: Watches the hard wired LAN connection.
‘ * When the LAN is CONNECTED, the Wireless adapter is DISABLED *
‘ * When the LAN is DISCONNECTED the Wireless adapter is ENABLED *
‘ Win XP & 7 & 8 supported. The function to enable/disable varies per OS.
‘
‘ EDIT : Eric van Voorthuizen, Grontmij NL
‘ EDITDATE: 11/01/2013
‘ EDITCOMM: Added W8 support, added filelogging (NateRice.com) and debuglevels , added LANG-support (NL/DE/SE), solved some minor bugs of not finding right WLAN-adapters, added WMI-filter
‘==========================================================================
Option Explicit
‘On Error Resume Next
Dim objShell
Dim bEnableLogging,bIncludeDateStamp,bPrependDateStampInLogFileName,sLogFileLocation,sLogFileName,sOverWriteORAppend,vLogMaximumLines,vLogMaximumSize,oLogFSO,sLogFile,oLogFile ,oReadLogFile, sFileContents
Dim aFileContents, sNow, oLogShell
Dim sLogToFile, OSFound, iSleep, sVersion
‘———LogToFile Configuration———
‘NOTE: Copy the configuration section To the beginning of an existing script. The values specified here must be set before calling the LogToFile sub.
‘You can disable logging globally by setting the bEnableLogging option to false.
bEnableLogging = True
‘Setting this to true will time stamp Each message that is logged to the log file with the current date and time.
bIncludeDateStamp = True
‘This will set the log file name to the current date and time. You can use this option to create incremental log files.
bPrependDateStampInLogFileName = False
‘Specify the log file location here. Path must contain a trailing backslash. If you would like to log to the same location as
‘the currently running script, set this value to “relative” or uncomment out the line below.
Set objShell = CreateObject( “WScript.Shell” )
sLogFileLocation = objShell.ExpandEnvironmentStrings(“%windir%”) & “\Temp\”
‘sLogFileLocation = “relative”
‘Specify the log file name here.
sLogFileName = Left(Wscript.ScriptName, Len(Wscript.ScriptName)-4) & “.log”
‘You can set whether or not you would like the script to append to an existing file, or if you would like it to overwrite existing copies.
‘To overwrite set the sOverWriteORAppend variable to “overwrite”
sOverWriteORAppend = “append”
‘Here you can set the maximum number of lines you like to record. If the maximum is reached the beginning of the log file
‘will be pruned. Setting this to a value of 0 will disable this function.
vLogMaximumLines = 0
‘This is just like limiting the log file to a number of lines but limits by the total size of the log file. This value
‘is in bytes. Setting this to 0 will disable this function.
vLogMaximumSize = 1000000
‘——-END LogToFile Configuration——-
Dim strComputer, objItem
Dim bCurrentStatus
Dim bWLANStatus
Dim bChanged
Dim strLANcard
Dim strWIRELESScard
Dim bDebug
bDebug=1
iSleep=30000
sVersion = “V1.4″
OSFound = FindOSType
‘Determine Network Adapter Names – See functions for details
If bDebug Then LogToFile sVersion & ” Start VBScript – Retrieve strLANcard”
strLANcard = GetLANName ‘”Local Area Connection”
If bDebug Then LogToFile “Retrieve strWIRELESScard”
strWIRELESScard = GetWirelessName ‘”Wireless Network Connection”
‘Verify the hard wired LAN adapter name exists
If (Not(AdapterExists(strLANcard))) Then
If bDebug Then LogToFile “WirelessDisableOnLAN – Could not find a physical network adapter: ” & strLANcard
‘WScript.Echo “NO physical LAN-adapter exist”
WScript.Quit(10)
End If
‘WScript.Echo strLANcard & ” present”
‘Verify the Wireless adapter name exists
If (Not(AdapterExists(strWIRELESScard))) Then
If bDebug Then LogToFile “WirelessDisableOnLAN – Could not find the network adapter: ” & strWIRELESScard
‘WScript.Echo “NO physical WIFI-adapter exist”
WScript.Quit(10)
End If
‘WScript.Echo strWIRELESScard & ” present”
If bDebug Then LogToFile “WirelessDisableOnLAN – Monitoring LAN connection: ” & strLANcard & ” – Toggling: ” & strWIRELESScard
‘Set initial value of bChanged to True
bChanged=True
‘MONITORING —————————————————————————–
While(True)
‘Msgbox “Press the ENTER key to continue. ”
If bDebug Then LogToFile “Rescan for networkconnection change”
If (bChanged) = True Then
‘WScript.Echo “Networkconnection has changed”
If bDebug Then LogToFile “Networkconnection has changed – [debug highlight]”
bChanged = False
bCurrentStatus = AdapterStatus(strLANcard)
bWLANStatus = AdapterStatus(strWIRELESScard)
If (bCurrentStatus) = True Then ‘Lan is connected
If bDebug Then LogToFile “Lan is connected strLANcard=” & strLANcard
If bWLANStatus = True Then ‘ If Wlan is connected then disable Wlan-adapter
If bDebug Then LogToFile “Lan is connected – WLAN will be disabled. strWIRELESScard=” & strWIRELESScard & “- [debug highlight]”
If OSFound = “Windows XP” Then EnableAdapterXP strWIRELESScard,False
If OSFound = “Windows 7” Or OSFound = “Windows 8” Then EnableAdapter7 strWIRELESScard,False
End If
Else ‘Lan is NOT connected
If bDebug Then LogToFile “Lan is not connected strLANcard=” & strLANcard
If bWLANStatus = False Then ‘if Wlan is not connected then enable Wlan-adapter
If bDebug Then LogToFile “Lan is NOT connected and wlan is not connected”
If OSFound = “Windows XP” Then EnableAdapterXP strWIRELESScard,True
If OSFound = “Windows 7” Or OSFound = “Windows 8” Then EnableAdapter7 strWIRELESScard,True
End If
End If
End If
If bDebug Then LogToFile “Sleep ” & iSleep/1000 & ” secs”
WScript.Sleep(iSleep)
If (bCurrentStatusAdapterStatus(strLANcard)) Then
If bDebug Then LogToFile “Status LANcard changed – [debug highlight]”
bChanged=True
End If
If (bWLANStatusAdapterStatus(strWIRELESScard)) Then
If bDebug Then LogToFile “Status WAN-connection changed – [debug highlight]”
bChanged=True
End If
Wend
‘MONITORING —————————————————————————–
Sub EnableAdapter7(sAdapterName, bStatus) ‘Adapter name, enable it true=yes
If bDebug Then LogToFile “Sub EnableAdapter7=” & “Param1:” & sAdapterName & “Param2:” & bStatus
Dim objWMIService, colItems
Set objWMIService = GetObject(“winmgmts:\\.\root\cimv2”)
Set colItems = objWMIService.ExecQuery(“Select * from Win32_NetworkAdapter”,,48)
For Each objItem in colItems
If bDebug=2 Then LogToFile “Controle gelijkheid – UCase(Trim(objItem.NetConnectionID))=” & UCase(Trim(objItem.NetConnectionID)) & “UCase(Trim(sAdapterName))=” & UCase(Trim(sAdapterName))
If (UCase(Trim(objItem.NetConnectionID)) = UCase(Trim(sAdapterName))) Then
If bDebug Then LogToFile “Is gelijk”
If (bStatus) = True Then
objItem.Enable
Else
objItem.Disable
End If
End If
Next
Set objWMIService=Nothing
Set colItems=Nothing
End Sub
Sub EnableAdapterXP(sAdapterName, bEnable)
‘WScript.Echo bEnable
If bDebug Then LogToFile “Sub EnableAdapterXP=” & “Param1:” & sAdapterName & “Param2:” & bEnable
Dim sShell, sCP, sAction, sNetwork
Dim sConn, sLANConn, sVerb
Dim sNetConn, sEnable, sDisable
Select Case (GetLocale)
Case 1043,2067 ‘NL en BE
sNetConn = “Netwerkverbindingen”
sEnable = “&Inschakelen”
sDisable = “&Uitschakelen”
Case 1053 ‘SE
sNetConn = “NĂ€tverksanslutningar”
sEnable = “&Aktivera”
sDisable =”&Inaktivera”
Case 1031 ‘DE
sNetConn = “Netzwerkverbindungen”
sEnable = “&Aktivieren”
sDisable = “&Deaktivieren”
Case Else
‘assume EN
sNetConn = “Network Connections”
sEnable = “En&able”
sDisable = “Disa&ble”
End Select
Set sShell = CreateObject(“Shell.Application”)
Set sCP = sShell.Namespace(3)
Set sNetwork = Nothing
‘Look for network connection folder
If bDebug Then LogToFile “Look for network connection folder”
For Each sConn in sCP.Items
If bDebug=2 Then LogToFile “Controle gelijkheid – sConn.Name=” & sConn.Name & “sNetConn =” & sNetConn
If sConn.Name = sNetConn Then
If bDebug Then LogToFile “Is gelijk” & sConn.GetFolder
Set sNetwork = sConn.GetFolder: Exit For
End If
Next
‘ Make sure we found it
If sNetwork Is Nothing Then
If bDebug Then LogToFile “Subroutine EnableAdapterXP – Could not find network folder”
‘WScript.Echo “Subroutine EnableAdapterXP – Could not find network folder”
WScript.Quit
End If
Set sLANConn = Nothing
If bDebug Then LogToFile “Reset sLANConn to Nothing”
‘ Find the connection by name
If bDebug Then LogToFile “Find the connection by name”
For Each sConn in sNetwork.Items
If bDebug=2 Then LogToFile “Controle gelijkheid – LCase(sConn.name)=” &LCase(sConn.name) & “LCase(sAdapterName) =” & LCase(sAdapterName)
If LCase(sConn.name) = LCase(sAdapterName) Then
Set sLANConn = sConn
If bDebug Then LogToFile “Set sLANConn to ” & sLANConn
Exit For
End If
Next
‘Error Check if Network Connection is found or not
If sLANConn is Nothing Then
If bDebug Then LogToFile “Could not find ” & sAdapterName
WScript.Quit
End If
‘ Find our enable or disable verb
For Each sVerb in sLANConn.verbs
If (bEnable) = True Then
‘WScript.Echo “bEnable is True” & sVerb.Name & sEnable
If sVerb.name = sEnable Then
If bDebug Then LogToFile “Enable Wlan-adapter” & sAdapterName
‘WScript.Echo “Enable”
Set sAction = sVerb
End If
Else
‘WScript.Echo “bEnable is False” & sVerb.Name & sDisable
If sVerb.name = sDisable Then
If bDebug Then LogToFile “Disable Wlan-adapter” & sAdapterName
‘WScript.Echo “Disable”
Set sAction = sVerb
End If
End If
Next
‘Now take action on our network card
If bDebug Then LogToFile “Now take action on our network card”
sAction.DoIt
If bDebug Then LogToFile “Sleep .. secs to prevents: A connection attempt is already in progress when attempting to re-enable the WLan adapter more than once before it’s ready.”
‘CleanUp
Set sShell = Nothing
Set sCP = Nothing
Set sNetwork = Nothing
Set sLANConn = Nothing
Set sAction = Nothing
WScript.Sleep(5000) ‘Prevents “A connection attempt is already in progress” when attempting to re-enable the WLan adapter more than once before it’s ready.
End Sub
‘AdapterStatus and AdapterExists subs are the same for both XP and Win 7
Function AdapterStatus( sAdapterName )
If bDebug Then LogToFile “Function AdapterStatus( sAdapterName )”
Dim objWMIService, colItems
Set objWMIService = GetObject(“winmgmts:\\.\root\cimv2”)
‘Set colItems = objWMIService.ExecQuery(“Select * from Win32_NetworkAdapter WHERE AdapterTypeID = 0 AND Manufacturer ‘Microsoft’ AND NOT PNPDeviceID LIKE ‘ROOT\\%’ “,,48)
Set colItems = objWMIService.ExecQuery(“Select * from Win32_NetworkAdapter”,,48)
If bDebug Then LogToFile “Reset AdapterStatus to False”
AdapterStatus = False
For Each objItem in colItems
If bDebug=2 Then LogToFile “Controle gelijkheid – UCase(Trim(objItem.NetConnectionID))=” & UCase(Trim(objItem.NetConnectionID)) & “UCase(Trim(sAdapterName))=” & UCase(Trim(sAdapterName))
If (UCase(Trim(objItem.NetConnectionID)) = UCase(Trim(sAdapterName))) Then
If bDebug Then LogToFile “Is gelijk dus AdapterStatus = (objItem.NetConnectionStatus=2) ‘Sets to -1 or True”
AdapterStatus = (objItem.NetConnectionStatus=2) ‘Sets to -1 or True
End If
Next
Set objWMIService = Nothing
Set colItems = Nothing
End Function
Function AdapterExists( sAdapterName )
If bDebug Then LogToFile “Function AdapterExists( sAdapterName )” & sAdapterName
Dim objWMIService, colItems
Set objWMIService = GetObject(“winmgmts:\\.\root\cimv2”)
‘Set colItems = objWMIService.ExecQuery(“Select * from Win32_NetworkAdapter”,,48)
Set colItems = objWMIService.ExecQuery(“Select * from Win32_NetworkAdapter WHERE Manufacturer ‘Microsoft’ AND NOT PNPDeviceID LIKE ‘ROOT\\%’ “,,48)
‘Select * from Win32_NetworkAdapter WHERE Manufacturer ‘Microsoft’ AND NOT PNPDeviceID LIKE ‘ROOT\\%’ “,,48
AdapterExists = False
‘WScript.Echo colItems.count
For Each objItem in colItems
If bDebug=2 Then LogToFile “Controle gelijkheid – UCase(Trim(objItem.NetConnectionID))=” & UCase(Trim(objItem.NetConnectionID)) & “UCase(Trim(sAdapterName))=” & UCase(Trim(sAdapterName))
If (UCase(Trim(objItem.NetConnectionID)) = UCase(Trim(sAdapterName))) Then
If bDebug Then LogToFile “Is gelijk dus AdapterExists = True”
AdapterExists = True
End If
Next
Set objWMIService = Nothing
Set colItems = Nothing
End Function
Function FindOSType
‘Defining Variables
Dim objWMI, objItem, colItems
Dim OSVersion, OSName, ProductType
‘Get the WMI object and query results
strComputer = “.”
Set objWMI = GetObject(“winmgmts:” & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”)
Set colItems = objWMI.ExecQuery(“Select * from Win32_OperatingSystem”,,48)
‘Get the OS version number (first two) and OS product type (server or desktop)
For Each objItem in colItems
OSVersion = Left(objItem.Version,3)
ProductType = objItem.ProductType
Next
‘Time to convert numbers into names
Select Case OSVersion
Case “6.2”
OSName = “Windows 8”
Case “6.1”
OSName = “Windows 7”
Case “6.0”
OSName = “Windows Vista”
Case “5.2”
OSName = “Windows 2003”
Case “5.1”
OSName = “Windows XP”
Case “5.0”
OSName = “Windows 2000”
Case “4.0”
OSName = “NT 4.0”
Case Else
OSName = “Windows ME”
End Select
‘Return the OS name
If bDebug Then LogToFile “Return the OS name=” & OSName
FindOSType = OSName
Set objWMI=Nothing
Set colItems=Nothing
End Function
Function GetWirelessName
If bDebug Then LogToFile “GetWirelessName”
‘To get the wireles adapter name, the registry is the most reliable method. WMI is not consistent enough to use Win32_NetworkAdapters\NetworkConnectionID
‘Win7 and XP both use PnpInstanceID – This can verify the adapter is Physical Hardware (prefix of PCI…)
‘Windows XP uses MediaSubtype (1=LAN, 2=Wireless)
‘Windows 7 also uses DefaultNameIndex. The lower the value indicates the first adapter, generally a DNI value of 0 will be the first created adapter.
‘Windows 7 also uses MediaSubType for Wireless, but not for LAN.
Dim strWirelessName
Dim strKeyPath, strComputer, objReg, arrSubKeys, SubKey
Dim DNIValue, PNPValue, MSTValue, strValue
Const HKLM=&H80000002
strComputer=”.”
strKeyPath=”SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}”
Set objReg=GetObject(“winmgmts:\\” & strComputer & “\root\default:StdRegProv”)
objReg.Enumkey HKLM ,strKeyPath,arrSubKeys
If OSFound = “Windows 7” Or OSFound = “Windows 8” Then
If bDebug Then LogToFile “W7/8”
For Each SubKey In arrSubKeys
objReg.GetDWORDValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” , “DefaultNameIndex”, DNIValue
If bDebug and Not IsNull(DNIValue) Then LogToFile “DefaultNameIndex:” & DNIValue
objReg.GetStringValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” , “PnpInstanceID”, PNPValue
If bDebug and Not IsNull(PNPValue) Then LogToFile “PnpInstanceID:” & PNPValue
objReg.GetDWORDValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” , “MediaSubType”, MSTValue
If bDebug and Not IsNull(MSTValue) Then LogToFile “MediaSubType:” & MSTValue
If Not IsNull(PNPValue) Then ‘Verify key exists
‘If Not IsNull(DNIValue) Then ‘Verify key exists
If MSTValue = “2” Then ‘Both Win7, Win8 and XP use MediaSubType of 2 for Wireless
If LEFT(UCase(PNPValue), 3) = “PCI” Then ‘Is Physical adapter (PCI\VEN_…) and…
‘If DNIValue=0 Then ‘…DefaultNameIndex is 0, then take the name
objReg.GetStringValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” ,”Name”,strValue
If bDebug Then LogToFile “W7/8 WLAN Name taken= ” & strValue
Exit For ‘Take first instance found
‘End If
End If
End If
‘End If
End If
Next
End If
If OSFound = “Windows XP” Then ‘Windows XP does not have DefaultNameIndex key
If bDebug Then LogToFile “XP”
For Each SubKey In arrSubKeys
objReg.GetStringValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” , “PnpInstanceID”, PNPValue
If bDebug and Not IsNull(PNPValue) Then LogToFile “PnpInstanceID:” & PNPValue
objReg.GetDWORDValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” , “MediaSubType”, MSTValue
If bDebug and Not IsNull(MSTValue) Then LogToFile “MediaSubType:” & MSTValue
If Not IsNull(PNPValue) Then ‘Verify key exists
If Not IsNull(MSTValue) Then ‘Verify MediaSubType key exists (XP)
If MSTValue = “2” Then ‘Both Win7, Win8 and XP use MediaSubType of 2 for Wireless
If LEFT(UCase(PNPValue), 3) = “PCI” Then ‘Is Physical adapter (PCI\VEN_…)
objReg.GetStringValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” ,”Name”,strValue
If bDebug Then LogToFile “XP WLAN Name taken= ” & strValue
Exit For ‘Take first instance found
End If
End If
End If
End If
Next
End If
strWirelessName = strValue
If bDebug Then LogToFile “strWirelessName = strValue: ” & strValue
If strValue = “” Then
strWirelessName = “AANNAME: Wireless Network Connection” ‘If all else fails, use default name
If bDebug Then LogToFile “strValue = EMPTY: strWirelessName assumed to ‘Wireless Network Connection'”
Else
If bDebug Then LogToFile “strValue = NOT EMPTY: ” & strWirelessName
End If
GetWirelessName= strWirelessName
End Function
Function GetLANName
If bDebug Then LogToFile “GetLANName”
‘To get the wireles adapter name, the registry is the most reliable method. WMI is not consistent enough to use Win32_NetworkAdapters\NetworkConnectionID
‘Win7 and XP both use PnpInstanceID – This can verify the adapter is Physical Hardware (prefix of PCI…)
‘Windows XP uses MediaSubtype (1=LAN, 2=Wireless)
‘Windows 7 Verifies the name isn’t the same as the Wireless card name (guarenteed name as it uses MediaSubType)
‘Windows 7 also uses MediaSubType for Wireless, but not for LAN.
Dim strLanName
Dim strKeyPath, strComputer, objReg, arrSubKeys, SubKey
Dim DNIValue, PNPValue, MSTValue, tempName, strValue
Const HKLM=&H80000002
strComputer=”.”
strKeyPath=”SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}”
Set objReg=GetObject(“winmgmts:\\” & strComputer & “\root\default:StdRegProv”)
objReg.Enumkey HKLM ,strKeyPath,arrSubKeys
If OSFound = “Windows 7” Or OSFound = “Windows 8” Then
If bDebug Then LogToFile “W7/8”
For Each SubKey In arrSubKeys
objReg.GetDWORDValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” , “DefaultNameIndex”, DNIValue
If bDebug and Not IsNull(DNIValue) Then LogToFile “DefaultNameIndex:” & DNIValue
objReg.GetStringValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” , “PnpInstanceID”, PNPValue
If bDebug and Not IsNull(PNPValue) Then LogToFile “PnpInstanceID:” & PNPValue
objReg.GetDWORDValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” , “MediaSubType”, MSTValue
If bDebug and Not IsNull(MSTValue) Then LogToFile “MediaSubType:” & MSTValue
objReg.GetStringValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” ,”Name”, tempName
If Not IsNull(PNPValue) Then ‘Verify key exists
‘If Not IsNull(DNIValue) Then ‘Verify key exists
If IsNull(MSTValue) Or MSTValue = “1” Then’Windows 7 MediaSubType must either not exist or be 1. No other values acceptable.
If LEFT(UCase(PNPValue), 3) = “PCI” Then ‘Is Physical adapter (PCI\VEN_…) and…
If Not tempName = GetWirelessName Then
objReg.GetStringValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” ,”Name”,strValue
If bDebug Then LogToFile “W7/8 LAN Name taken= ” & strValue
Exit For ‘Take first instance found
End If
End If
End If
‘End If
End If
Next
End If
If OSFound = “Windows XP” Then ‘Windows XP can rely on MediaSubType value of 1
If bDebug Then LogToFile “XP”
For Each SubKey In arrSubKeys
objReg.GetStringValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” , “PnpInstanceID”, PNPValue
If bDebug and Not IsNull(PNPValue) Then LogToFile “PnpInstanceID:” & PNPValue
objReg.GetDWORDValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” , “MediaSubType”, MSTValue
If bDebug and Not IsNull(MSTValue) Then LogToFile “MediaSubType:” & MSTValue
If Not IsNull(PNPValue) Then ‘Verify key exists
If Not IsNull(DNIValue) Then ‘Verify key exists
If IsNull(MSTValue) Or MSTValue = “1” Then’Windows XP uses 1 for LAN MediaSubType
If LEFT(UCase(PNPValue), 3) = “PCI” Then ‘Is Physical adapter (PCI\VEN_…)
objReg.GetStringValue HKLM,strKeyPath & “\” & SubKey & “\” & “Connection” ,”Name”,strValue
If bDebug Then LogToFile “XP LAN Name taken= ” & strValue
Exit For ‘Take first instance found
End If
End If
End If
End If
Next
End If
strLanName = strValue
‘*********
If strValue = “” Then
strLanName = “AANNAME: Local Area Connection” ‘If all else fails, use default name
If bDebug Then LogToFile “strValue = EMPTY: strLanName assumed to ‘Local Area Connection'”
Else
If bDebug Then LogToFile “strValue = NOT EMPTY: ” & strLanName
End If
GetLANName = strLanName ‘Return the value of the LAN connection
End Function
Sub LogToFile(Message)
If bEnableLogging = False Then Exit Sub
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Set oLogFSO = CreateObject(“Scripting.FileSystemObject”)
If sLogFileLocation = “relative” Then
Set oLogShell = CreateObject(“Wscript.Shell”)
sLogFileLocation = oLogShell.CurrentDirectory & “\”
Set oLogShell = Nothing
End If
If bPrependDateStampInLogFileName Then
sNow = Replace(Replace(Now(),”/”,”-“),”:”,”.”)
sLogFileName = sNow & ” – ” & sLogFileName
bPrependDateStampInLogFileName = False
End If
sLogFile = sLogFileLocation & sLogFileName
If sOverWriteORAppend = “overwrite” Then
Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForWriting, True)
sOverWriteORAppend = “append”
Else
Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForAppending, True)
End If
If bIncludeDateStamp Then
Message = Now & ” ” & Message
End If
oLogFile.WriteLine(Message)
oLogFile.Close
If vLogMaximumLines > 0 Then
Set oReadLogFile = oLogFSO.OpenTextFile(sLogFile, ForReading, True)
sFileContents = oReadLogFile.ReadAll
aFileContents = Split(sFileContents, vbCRLF)
If Ubound(aFileContents) > vLogMaximumLines Then
sFileContents = Replace(sFileContents, aFileContents(0) & _
vbCRLF, “”, 1, Len(aFileContents(0) & vbCRLF))
Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForWriting, True)
oLogFile.Write(sFileContents)
oLogFile.Close
End If
oReadLogFile.Close
End If
If vLogMaximumSize > 0 Then
Set oReadLogFile = oLogFSO.OpenTextFile(sLogFile, ForReading, True)
sFileContents = oReadLogFile.ReadAll
oReadLogFile.Close
sFileContents = RightB(sFileContents, (vLogMaximumSize*2))
Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForWriting, True)
oLogFile.Write(sFileContents)
oLogFIle.Close
End If
oLogFSO = Null
End Sub
Hi Eric, Can you attach the revised vbs script here? Tried copying and pasting the text above, but having issues with the formatting, not sure if the syntax is incorrect?? Probably something really simple….
Hi Peter,
One thing to look out for is the double quotes. It seems our blog software uses a different double quote that is not compatible with VB script, so you just need to go through the script and replace them by hand.
Thanks Steve, I will give this a go and let you know!
Hello,
Very nice script!
Is it also possible to do a dhcp release before the adapter is put to disabled?
Anyone know how to add this to this script?
Kind regards,
remco
Friends how about WiredWiFiSwitcher?
i try this on my 32 bit windows 7 its work but its doesn’t work on 64,i don’t no why .please anyone could help me?
and anything simeler software for enable and disable wifi like bridge ceker or WiredWiFiSwitcher plese write the comment below.
Thanks in advance.