Search code examples
vbscriptwmi

Reset Network Adapter


I have here a VBScript to "toggle" my network adapter (built from a script found on the Internet).

I was wondering if maybe someone can help me convert it to a script that can "reset" (disable, then re-enable) my wireless adapter, rather than toggle it.

'~ Toggle a SPECIFIED NIC on or off
Option Explicit

Const NETWORK_CONNECTIONS = &H31&

Dim objShell, objFolder, objFolderItem, objEnable, objDisable
Dim folder_Object, target_NIC
Dim NIC, clsVerb
Dim str_NIC_Name, strEnable, strDisable
Dim bEnabled, bDisabled

'NIC name goes here VVV
str_NIC_Name = "Wi-Fi"

strEnable = "En&able"
strDisable = "Disa&ble"

' create objects and get items
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(NETWORK_CONNECTIONS)
Set objFolderItem = objFolder.Self
Set folder_Object = objFolderItem.GetFolder

Set target_NIC = Nothing

' look at each NIC and match to the chosen name
For Each NIC In folder_Object.Items
    If LCase(NIC.Name) = LCase(str_NIC_Name) Then
        ' proper NIC is found, get it
        Set target_NIC = NIC
    End If
Next

bEnabled = True
Set objEnable = Nothing
Set objDisable = Nothing

For Each clsVerb In target_NIC.Verbs
    '~ Wscript.Echo clsVerb
    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 change
WScript.Sleep 5000

Solution

  • I think it's better to use WMI (Windows Management Instrumentation).

    Here is a sample script:

    Option Explicit
    
    dim ComputerName
    dim WMIService, NIC
    dim ConnectionName
    
    ComputerName = "."
    ConnectionName = "Ethernet"
    
    if not IsElevated then 
        WScript.Echo "Please run this script with administrative rights!"
        WScript.Quit
    end if
    
    On Error Resume Next
    
    Set WMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ComputerName & "\root\cimv2")
    Set NIC = WMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID = '" & ConnectionName & "'").ItemIndex(0)
    
    if NIC is nothing then
        WScript.Echo "NIC not found!"
        WScript.quit
    end if
    
    WScript.Echo "NIC Current status: " & iif(NIC.NetEnabled, "Enabled", "Disabled") & vbcrlf
    
    if NIC.NetEnabled then
        WScript.Echo "Disabling NIC..."
        NIC.Disable
        WScript.Sleep 1000
        WScript.Echo "Enabling NIC..."
        NIC.Enable
    end if
    
    function iif(cond, truepart, falsepart)
        if cond then iif=truepart else cond=falsepart
    end function
    
    function IsElevated()
    
        On Error Resume Next
        CreateObject("WScript.Shell").RegRead("HKEY_USERS\s-1-5-19\")
        IsElevated = (err.number = 0)
    
    end function