Jump to content
Sign in to follow this  
ineleganthack

Set NIC 100/Full or Auto based on Auto linkspeed obtained.

Recommended Posts

ineleganthack

(first code post ever)

Problem: I support a Windows 7/XP environment with about 1400 mostly Dell PCs managed by LANDesk. PCs are connected to two kinds of switches: Cisco switches that require 100/Full NIC connections to not get really awful 100/Half on Auto, and Brocade switches that support Gigabit connections and can do auto negotiation. Trick is, I don't have a way to tell from desk number, user, or subnet which one a given PC is connected to, and the PCs move from one type to another.

Solution: I wrote this script to set a PC's NIC to auto, and check what linkspeed it gets. If it gets 1000, it stays auto. If it gets 100, it gets set to 100/full. By default, results are written to a key LANDesk monitors, but  you could easily change this if you want.

Since NIC registry settings vary by NIC and driver version, I had to make up a list of known NIC settings in my environment. You'll probably have to expand this for your environment, which is done by editing the attached .reg file.

It is meant to be run via command line arguements. Launch the executable with /help for supported arguments.

The .bat installer includes a registry Run key so that the script can check on login if the PC's subnet has changed, and run its tests if so. Otherwise, it just quietly goes away and does nothing. There are also sample commands to force it to run on install (if switches or PC connections are known to have been changed), or to force it to run only if it has never run before.

There is a GUI that can be set to show in detail what is going on or be greatly simplified for typical end users.

Everything is logged for troubleshooting.

Since WMI is imperfect, at any given time I have about 10 PCs or so that throw an error because WMI is not behaving. To be expected in an environment with images up to 6+ years old. Also, if a NIC is not known, you get an error. Other than that, works great and has helped a lot in my usage.

Hopefully someone else can get some use from this.

#region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=Icon\Ethernet-Ethernet-on-icon Green Fill.ico
#AutoIt3Wrapper_Outfile=c:\temp\Nic Speed Optimizer.exe
#AutoIt3Wrapper_Res_Comment=Nic set Auto or 100/Full by linkspeed. Tested on XP and Windows 7.
#AutoIt3Wrapper_Res_Description=By InelegantHack, 2013
#AutoIt3Wrapper_Res_Fileversion=2.0.0.7
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=y
#AutoIt3Wrapper_Res_Language=1033
#AutoIt3Wrapper_Run_After=copy "%out%" "..\"
#AutoIt3Wrapper_Run_Tidy=y
#endregion ;**** Directives created by AutoIt3Wrapper_GUI ****
;Icon credit http://www.iconarchive.com/show/icons8-metro-style-icons-by-visualpharm/Ethernet-Ethernet-on-icon.html Thanks to http://www.visualpharm.com/

#include-once

#include <WindowsConstants.au3>
#include <GUIConstantsEx.au3>
#include <EditConstants.au3>
#include <StaticConstants.au3>
#include <GuiEdit.au3>
#include <array.au3>
#include <Misc.au3>

Opt("TrayAutoPause", 0)
Opt("TrayIconHide", 1)
TraySetToolTip("Network connection optimization in progress")

Global $sRegStatusPath = "HKLM\SOFTWARE\Intel\LANDesk\Inventory\Custom Fields"
Local $sWMIComputer = "localhost", $sRegAdaptorKeyPath = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}"
Local $sOldGateway
Local $oComError, $oWMI, $oCIMV2
Local $aNetworkAdaptorDetails, $aKnownAdaptorDescripts
Local $sKnownNic, $sHelpMessage, $sFinalNote, $sLogFilePath
Local $shNormalColor = 0xB09160, $shSuccessfulDoneColor = 0xB0FF62, $shErrorColor = 0xFF8080
Local $bConnected = False, $bAutoStartupMode = False, $bShowHelp = False, $bBadArguments = False
Local $bSimpleUI = False, $bSettingsChanged = False, $bRunLANDeskOnEnd = False
Local $hfLog
Local $hgNetOptStatus
Local $heGuiDetails
Local $hlMainSimpleLabel
Local $nGuiFontMultiplier = 1.8, $nScriptVersion = FileGetVersion(@ScriptFullPath)
Local $iBigFontSize = 14, $iMedFontSize = 12, $iSmallFontSize = 11, $iGuiSpaceDivider = 20, $iSuppressErrors = 0
Local $iTimeoutStandardError = 60, $iTimeoutCriticalError = 0, $iResultViewTime = 15, $iStartupPromptTime = 0
Local $iDisconnectResult, $iGUIWidth = 800, $iGuiBigLabelHeight = $iBigFontSize * $nGuiFontMultiplier, $iGuiSmallLabelHeight = $iSmallFontSize * $nGuiFontMultiplier
Local $iGuiMedLabelHeight = $iSmallFontSize * $nGuiFontMultiplier, $iGuiDetailHeight = 95
Local $iGuiHBufferSpace = 10, $iGuiVPos = $iGuiHBufferSpace
Local $iLabelWidth = $iGUIWidth - ($iGuiHBufferSpace * 2)
Local $iGuiHeight = $iGuiVPos + $iGuiBigLabelHeight + 30 ;Kluge +30 to account for top modal frame bar
Local $aFinalStatus[1][14]
$aFinalStatus[0][0] = 0
Const $wbemFlagReturnImmediately = 0x10, $wbemFlagForwardOnly = 0x20
Const $sEnableVerb = "En&able", $sDisableVerb = "Disa&ble", $sNetConnectionSystemName = "Network Connections"; Windows XP

OnAutoItExitRegister("_EndScriptCleanUp")
$oComError = ObjEvent("AutoIt.Error", "_ComErrorHandler") ; Install a custom error handler

$hgNetOptStatus = GUICreate("Network Speed Optimizer", $iGUIWidth, $iGuiHeight, -1, 30, $DS_MODALFRAME, $WS_EX_TOPMOST)
GUISetBkColor($shNormalColor, $hgNetOptStatus)
$hlMainSimpleLabel = GUICtrlCreateLabel("Checking your PC for the best network speed.", $iGuiHBufferSpace, $iGuiVPos, $iLabelWidth, $iGuiBigLabelHeight, $SS_CENTER)
GUICtrlSetFont(-1, $iBigFontSize, 800)
GUICtrlSetResizing(-1, $GUI_DOCKALL)
$iGuiVPos = $iGuiVPos + $iGuiBigLabelHeight ;+ $iGuiHBufferSpace
$heGuiDetails = GUICtrlCreateEdit("", 0, $iGuiVPos, $iGUIWidth - 5, $iGuiDetailHeight, BitOR($WS_VSCROLL, $ES_READONLY))
GUICtrlSetResizing($heGuiDetails, $GUI_DOCKMENUBAR)
GUICtrlSetState($heGuiDetails, @SW_HIDE)

$sLogFilePath = RegRead("HKLM64\SOFTWARE\NIC Speed Optimizer", "Log File")
If $sLogFilePath = "" Then $sLogFilePath = @TempDir & "\Nic Speed Optimizer.log"
$hfLog = FileOpen($sLogFilePath, 10)

_UpdateStatus(@MON & "/" & @MDAY & "/" & @YEAR & " NIC Speed Optimizer " & $nScriptVersion & " written by InelegantHack, 2013" & @LF)
_UpdateStatus("This information will be logged to '" & $sLogFilePath & "'" & @LF)
_UpdateStatus("Processing command line arguments." & @LF)

For $i = 1 To $CmdLine[0]
    _UpdateStatus("Processing argument '" & $CmdLine[$i] & "'" & @LF)
    If $CmdLine[$i] = "?" Or $CmdLine[$i] = "/?" Or $CmdLine[$i] = "help" Or $CmdLine[$i] = "/help" Then
        $bShowHelp = True
        _UpdateStatus("Argument '" & $CmdLine[$i] & "' received. Showing Help prompt." & @LF)
    ElseIf $CmdLine[$i] = "/AutoStartupMode" Then
        $bAutoStartupMode = True
        $iStartupPromptTime = -1
        _UpdateStatus("'/AutoStartupMode' argument received. Running in automatic startup check mode." & @LF)
    ElseIf $CmdLine[$i] = "/SimpleUI" Then
        $bSimpleUI = True
        _UpdateStatus("'/SimpleUI' argument received. Showing basic details only." & @LF)
    ElseIf StringInStr($CmdLine[$i], "/StartPromptTime=") = 1 Then ; $CmdLine[$i] = "/StartPromptTime" Then
        $iStartupPromptTime = Number(StringMid($CmdLine[$i], 18))
        If $iStartupPromptTime = -1 Then
            _UpdateStatus($CmdLine[$i] & " argument received. Startup prompt will be skipped." & @LF)
        ElseIf $iStartupPromptTime = 0 Then
            _UpdateStatus($CmdLine[$i] & " argument received. Startup prompt will display until user clicks OK. (Non-numerical values will be treated as 0)" & @LF)
        Else
            _UpdateStatus($CmdLine[$i] & " argument received. Startup prompt will display for up to " & $iStartupPromptTime & " seconds." & @LF)
        EndIf
    ElseIf StringInStr($CmdLine[$i], "/ResultViewTime=") = 1 Then
        $iResultViewTime = Number(StringMid($CmdLine[$i], 17))
        If $iResultViewTime = 0 Then
            _UpdateStatus($CmdLine[$i] & " argument received. Results will display until user clicks OK." & @LF)
        ElseIf $iResultViewTime = -1 Then
            _UpdateStatus($CmdLine[$i] & " argument received. Result prompt will be skipped." & @LF)
        Else
            _UpdateStatus($CmdLine[$i] & " argument received. Result prompt will display for up to " & $iResultViewTime & " seconds." & @LF)
        EndIf
    ElseIf StringInStr($CmdLine[$i], "/StandardErrorTimeOut=") = 1 Then
        $iTimeoutStandardError = Number(StringMid($CmdLine[$i], 23))
        If $iTimeoutStandardError = -1 Then
            If $iSuppressErrors <> 2 Then $iSuppressErrors = 1 ;Don't allow to owerride suppressing all messages.
            _UpdateStatus($CmdLine[$i] & " argument received. Standard error prompts will be skipped." & @LF)
        Else
            $iTimeoutStandardError = Int($iTimeoutStandardError)
            If $iTimeoutStandardError = 0 Then
                _UpdateStatus($CmdLine[$i] & " argument received. Standard errors will display until user clicks OK. (Non-numerical values will be treated as 0)" & @LF)
            Else
                _UpdateStatus($CmdLine[$i] & " argument received. Standard error messages will display for up to " & $iTimeoutStandardError & " seconds." & @LF)
            EndIf
        EndIf
    ElseIf StringInStr($CmdLine[$i], "/CriticalMessageTimeout=") = 1 Then
        $iTimeoutCriticalError = Number(StringMid($CmdLine[$i], 25))
        If $iTimeoutCriticalError = -1 Then
            $iSuppressErrors = 2
            _UpdateStatus($CmdLine[$i] & " argument received. All message prompts will be skipped." & @LF)
        Else
            $iTimeoutCriticalError = Int($iTimeoutCriticalError)
            If $iTimeoutCriticalError = 0 Then
                _UpdateStatus($CmdLine[$i] & " argument received. Critical messages will display until user clicks OK. (Non-numerical values will be treated as 0)" & @LF)
            Else
                _UpdateStatus($CmdLine[$i] & " argument received. Critical messages will display for up to " & $iTimeoutCriticalError & " seconds." & @LF)
            EndIf
        EndIf
    Else
        _UpdateStatus("Unknown argument '" & $CmdLine[$i] & "' received. This will be ignored" & @LF, 2)
        $bBadArguments = True
        $bShowHelp = True
    EndIf
Next

If _Singleton("Test Unique", 1) = 0 Then
    If Not $iSuppressErrors Then MsgBox(16, "Network Optimization Duplicate Script Error", "An instance of this script is already running." & @LF & _
            "Only one instance is allowed.", $iTimeoutStandardError)
    Exit
EndIf

;~ MsgBox(0, "About to resize", "Test")
If $bSimpleUI = False Then
    $iGuiHeight = $iGuiHeight + $iGuiDetailHeight
    WinMove($hgNetOptStatus, "", Default, Default, Default, $iGuiHeight)
    GUICtrlSetState($heGuiDetails, @SW_ENABLE + @SW_SHOW)
EndIf

$sHelpMessage = "/? or /Help (or invalid argument)" & @LF & _
        "     Display this message" & @LF & _
        @LF & _
        "/SimpleUI" & @LF & _
        "     Show only very basic informtion in GUI during configuration." & @LF & _
        @LF & _
        "/AutoStartupMode" & @LF & _
        "     Silently checks if PC has never been checked or has a new gateway." & @LF & _
        "     If either condition is true, shows GUI and checks speed settings." & @LF & _
        "     Ideal for using in a run key at startup before network apps can run." & @LF & _
        "     /StartPromptTime=-1 will be set automatically unless" & @LF & _
        "     /StartPromptTime=x is set to 0 or higher AFTER this argument." & @LF & _
        @LF & _
        "/StartPromptTime=x" & @LF & _
        "     Display start message for x seconds cautioning to close applications." & @LF & _
        "     Use 0 to wait until user clicks OK (default), or -1 to suppress." & @LF & _
        @LF & _
        "/ResultViewTime=x" & @LF & _
        "     View final script results for x Seconds. Default 15, use 0 to" & @LF & _
        "     leave prompt until user clicks OK, -1 for no prompt." & @LF & _
        @LF & _
        "/StandardErrorTimeOut=x" & @LF & _
        "     Timout in x seconds to show standard error messages (Default " & $iTimeoutStandardError & ")." & @LF & _
        "     Use /StandardErrorTimeOut=-1 to suppress standard errors." & @LF & _
        @LF & _
        "/CriticalMessageTimeout=x" & @LF & _
        "     Timeout in x seconds to show critical error messages." & @LF & _
        "     Default is 0 seconds (no timeout--leaves prompt until it is clicked)." & @LF & _ ;$iTimeoutCriticalError
        "     Use /CriticalMessageTimeout=-1 to suppress all errors." & @LF & _
        "     Implies /StandardErrorTimeOut=-1." & @LF & _
        "     Add /ResultViewTime=-1 and /StartPromptTime=-1 to suppress" & @LF & _
        "     all prompts." & @LF & _
        "     Note that this help message will be treated as a critical message" & @LF & _
        "     (shown on invalid arguments). Test before deploying!"

If $bBadArguments = True Then
    $sHelpMessage = "Unknown argument(s) '" & $CmdLineRaw & "' received." & @LF & @LF & $sHelpMessage
    _UpdateStatus($sHelpMessage & @LF)
EndIf

If $bShowHelp = True Then
    If $iSuppressErrors < 2 Then MsgBox(32, "Valid Network Speed Optimizer switches", $sHelpMessage, $iTimeoutCriticalError)
    Exit
EndIf

If $iStartupPromptTime <> -1 Then
    _UpdateStatus("Prompting for OK before continuing." & @LF)
    If MsgBox(49, "Network disconnect warning: CLOSE ALL PROGRAMS NOW!", _
            "BE SURE TO CLOSE ANY NETWORK FILES OR WEB APPLICATIONS BEFORE CONTINUING!" & @LF & @LF & _
            "Click OK to make sure your PC has the best settings.", $iStartupPromptTime) <> 1 Then Exit
EndIf

If $bAutoStartupMode = False Then
    _UpdateStatus("Showing GUI and tray icon." & @LF)
    Opt("TrayIconHide", 0)
    GUISetState(@SW_SHOW)
EndIf

_UpdateStatus("Clearing any domain suffix entries to fix Checkpoint-created errors." & @LF)
RegDelete("HKLM64\SYSTEM\CurrentcontrolSet\services\Tcpip\Parameters", "SearchList")

_UpdateStatus("Getting base WMI object." & @LF)
$oWMI = ObjGet("winmgmts:\\" & $sWMIComputer & "\root\WMI")
If Not IsObj($oWMI) Then
    _UpdateStatus("Unable to get WMI object. Script cannot continue." & @LF, 2)
    Exit
EndIf

_UpdateStatus("Getting CIMV2 WMI object." & @LF)
$oCIMV2 = ObjGet("winmgmts:\\" & $sWMIComputer & "\root\CIMV2")
If Not IsObj($oCIMV2) Then
    _UpdateStatus("Unable to get CIMv2 WMI object. Script cannot continue." & @LF, 2)
    Exit
EndIf

Dim $aKnownAdaptorDescripts[1]
For $i = 1 To 9999
    $sKnownNic = RegEnumKey("HKLM64\SOFTWARE\NIC Speed Optimizer\Known NICs", $i)
    If @error <> 0 Then ExitLoop
    ReDim $aKnownAdaptorDescripts[$i + 1]
    $aKnownAdaptorDescripts[$i] = $sKnownNic
Next
$aKnownAdaptorDescripts[0] = UBound($aKnownAdaptorDescripts) - 1

If $aKnownAdaptorDescripts[0] = 1 Then
    _UpdateStatus("Unable to find settings for your network adaptor." & @LF, 2); & _
;~          "Contact the Helpdesk to ensure you have the best settings for your network port and adaptor!" & @LF, 2)
    Exit
EndIf

;~ MsgBox(0, "Test", "GUI created.")
;_ArrayDisplay($aKnownAdaptorDescripts, "Known adaptor settings")
_UpdateStatus("Getting preliminary NIC status." & @LF)
_GetNICStatus()
;~ _ArrayDisplay($aNetworkAdaptorDetails, "Found network adaptor details")
If $bAutoStartupMode = True Then
    For $i = 1 To $aNetworkAdaptorDetails[0][0]
        If $aNetworkAdaptorDetails[$i][9] = "" Then ContinueLoop
        $sOldGateway = RegRead("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$i][5], "Gateway")
        If $sOldGateway = $aNetworkAdaptorDetails[$i][9] And _
                $aNetworkAdaptorDetails[$i][18] = "Connected" Then
            ;Gateway has not changed. Exit now.
            _UpdateStatus("Gateway unchanged. Exiting script." & @LF)
            Exit
        Else
            _UpdateStatus("Gateway changed from " & $sOldGateway & " to " & $aNetworkAdaptorDetails[$i][9] & ". Checking speed settings." & @LF)
        EndIf
    Next
EndIf

If $bAutoStartupMode = True Then ;If we have suppressed the GUI until now, show it so user knows we'll be disconnecting them.
    _UpdateStatus("Unhiding GUI and tray icon to show status while NIC is checked." & @LF)
    Opt("TrayIconHide", 0)
    GUISetState(@SW_SHOW)
EndIf

For $a = 1 To $aNetworkAdaptorDetails[0][0] ;;;;Enable disabled active adaptors;;;;
    If $aNetworkAdaptorDetails[$a][4] = "" Then ContinueLoop
    If $aNetworkAdaptorDetails[$a][4] = "Disabled" Then ;Enable any disabled adaptors.
        _UpdateStatus("Adaptor '" & $aNetworkAdaptorDetails[$a][2] & "' is currently disabled! Attempting to enable." & @LF)
        GUICtrlSetData($aNetworkAdaptorDetails[$a][25], "Adaptor is currently disabled! Attempting to enable.")
        If _NicEnableDisable($aNetworkAdaptorDetails[$a][5], "Enable") <> "Enabled" Then ;_NICContol($aNetworkAdaptorDetails[$a][5], 3) <> 1 Then
            _UpdateStatus("Unable to enable network adaptor '" & $aNetworkAdaptorDetails[$a][2] & "'" & @LF, 1); & _
;~                  "If you cannot access the network when this script is over, call the Helpdesk." & @LF, 1)
            GUICtrlSetData($aNetworkAdaptorDetails[$a][25], "Unable to activate disabled adaptor! If you cannot access the network when this script is over, call the Helpdesk.")
        Else
            GUICtrlSetData($hlMainSimpleLabel, "Please wait while your network card is optimized. Waiting for connection.")
            If _IPAddressWait($a) = 1 Then
                GUICtrlSetData($hlMainSimpleLabel, "Please wait while your network card is optimized. Connection successful.")
            EndIf
        EndIf
        _GetNICStatus($aNetworkAdaptorDetails[$a][6])
    EndIf
Next

If _CheckForConnection(True) = -1 Then ;Find out if we even have a wired connection before contintuing.
    If $bAutoStartupMode = True Then
        _UpdateStatus("No wired connection found, and running in auto startup mode, so exiting now. Nothing to do here." & @LF)
        Exit
    EndIf
EndIf

For $a = 1 To $aNetworkAdaptorDetails[0][0] ;;;;Set all active adaptors to Auto;;;;
    _UpdateStatus("Checking that adaptor " & $aNetworkAdaptorDetails[$a][2] & ", currently set to " & _
            $aNetworkAdaptorDetails[$a][10] & " with linkspeed " & $aNetworkAdaptorDetails[$a][1] & ", is set to auto." & @LF)
    If $aNetworkAdaptorDetails[$a][10] = "" Then
        _UpdateStatus("Skipping adaptor " & $aNetworkAdaptorDetails[$a][2] & "because the current linkspeed was not found." & @LF)
    ElseIf $aNetworkAdaptorDetails[$a][10] <> "Auto" Then ;Set to Auto first no matter what.
        _SetAdaptorSpeed("Auto", $a)
    EndIf
Next

GUICtrlSetData($hlMainSimpleLabel, "Please wait while your network card is optimized. Testing automatic speed.")

_UpdateStatus("Done checking initial adaptor speed. Refreshing adaptor status." & @LF)
_GetNICStatus()
_UpdateStatus("Data updated. Checking to ensure we have a connection." & @LF)
_CheckForConnection() ;Make sure we have an active connection before we continue.

For $a = 1 To $aNetworkAdaptorDetails[0][0];;;;Check if Auto gets 100, if so change to 100/Full; otherwise, leave at auto;;;;
    If $aNetworkAdaptorDetails[$a][19] = "" Then
        _UpdateStatus("Skipping unknown adaptor '" & $aNetworkAdaptorDetails[$a][19] & "' because speed settings are not available." & @LF)
        ContinueLoop
    EndIf
    _UpdateStatus("Checking adaptor " & $aNetworkAdaptorDetails[$a][2] & ", currently set to " & _
            $aNetworkAdaptorDetails[$a][19] & " with linkspeed " & $aNetworkAdaptorDetails[$a][17] & " speed, and updating settings if needed." & @LF)
    If $aNetworkAdaptorDetails[$a][17] = "1000" Then ;Current link speed is gigabit.
        _CheckForConnection() ;Make sure we have an active connection before we continue.
        _UpdateStatus("* Gigabit connection achieved. Keeping adaptor at automatic speed and duplex." & @LF)
        GUICtrlSetData($aNetworkAdaptorDetails[$a][25], "Gigabit connection achieved. Keeping adaptor at automatic speed and duplex.")
        GUICtrlSetData($hlMainSimpleLabel, "Please wait while your network card is optimized. Keeping automatic speed.")
    ElseIf $aNetworkAdaptorDetails[$a][17] = "100" Then ;Current link speed is 100 while adaptor at Auto setting. Set to 100/Full.
        _SetAdaptorSpeed("100/Full", $a)
        _UpdateStatus("* Refreshing adaptor data." & @LF)
        GUICtrlSetData($aNetworkAdaptorDetails[$a][25], "Refreshing adaptor settings.")
        _GetNICStatus($aNetworkAdaptorDetails[$a][6])
    Else ;On Auto did not get gigabit or 100 speed. Something awkward is going on. Leave at auto. For example, switch set to 10 speed for old Jetdirect card.
        _UpdateStatus("* Doing nothing because current linkspeed '" & $aNetworkAdaptorDetails[$a][17] & "' on row " & $a & _
                " is not defined to set as a new speed." & @LF)
        GUICtrlSetData($aNetworkAdaptorDetails[$a][25], "Leaving adaptor as is because current linkspeed '" & $aNetworkAdaptorDetails[$a][17] & _
                " is not defined to set as a new speed.")
    EndIf

    _CheckForConnection() ;Make sure we have an active connection before we continue.

    ;Stamp results to registry for reference next time running and LANDesk reporting.
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status", "Last Full Check", "Reg_SZ", _
            @MON & "/" & @MDAY & "/" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC)
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "LinkSpeed", "Reg_SZ", $aNetworkAdaptorDetails[$a][17])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Last LinkSpeed", "Reg_SZ", $aNetworkAdaptorDetails[$a][1])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Adaptor Setting", "Reg_SZ", $aNetworkAdaptorDetails[$a][19])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Last Adaptor Setting", "Reg_SZ", $aNetworkAdaptorDetails[$a][10])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Status", "Reg_SZ", $aNetworkAdaptorDetails[$a][18])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Last Status", "Reg_SZ", $aNetworkAdaptorDetails[$a][4])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Adaptor Description", "Reg_SZ", $aNetworkAdaptorDetails[$a][2])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Active?", "Reg_SZ", $aNetworkAdaptorDetails[$a][7])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "IP Address", "Reg_SZ", $aNetworkAdaptorDetails[$a][8])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Gateway", "Reg_SZ", $aNetworkAdaptorDetails[$a][9])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Plug and Play ID", "Reg_SZ", $aNetworkAdaptorDetails[$a][15])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Service Name", "Reg_SZ", $aNetworkAdaptorDetails[$a][16])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Note", "Reg_SZ", $aNetworkAdaptorDetails[$a][20])
    RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer\Status\" & $aNetworkAdaptorDetails[$a][5], "Reg Key", "Reg_SZ", $aNetworkAdaptorDetails[$a][22])

    If $aNetworkAdaptorDetails[$a][18] <> "Connected" And $bConnected = True Then ;If the current adaptor is not connected, but another one is, then
        ;don't bother writing to the registry (skip logging LANDesk status for unused adaptor). We only want the active one. If another adaptor is NOT
        ;connected ($bConnected = False) then log the adaptor with the error status.
        _UpdateStatus("Skipping LANDesk keys for adaptor " & $aNetworkAdaptorDetails[$a][2] & " with status " & $aNetworkAdaptorDetails[$a][18] & "." & @LF)
        ContinueLoop
    EndIf

    RegWrite($sRegStatusPath, "Nic Optimized As", "Reg_SZ", $aNetworkAdaptorDetails[$a][19] & _
            ":" & $aNetworkAdaptorDetails[$a][17])
    RegWrite($sRegStatusPath, "Nic Speed Set Date", "Reg_SZ", _
            @MON & "/" & @MDAY & "/" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC)
    RegWrite($sRegStatusPath, "Nic Speed Optimizer Version", "Reg_SZ", $nScriptVersion)
Next

;_ArrayDisplay($aNetworkAdaptorDetails, "Final network adaptor details")
For $a = 1 To $aNetworkAdaptorDetails[0][0]
    If $aNetworkAdaptorDetails[$a][20] <> "Unchanged" Then $bSettingsChanged = True
    $sFinalNote = $sFinalNote & $aNetworkAdaptorDetails[$a][2] & ": " & $aNetworkAdaptorDetails[$a][20] & @LF
Next
_UpdateStatus($sFinalNote)
;MsgBox(64, "Done checking network adaptor speed.", "Result:" & @LF & $sFinalNote)
RegWrite($sRegStatusPath, "Nic Speed Setting Note", "Reg_SZ", StringReplace($sFinalNote, @LF, " "))
If $iResultViewTime = 0 Then
    _UpdateStatus("Prompting with results and waiting for an OK before closing." & @LF)
ElseIf $iResultViewTime = -1 Then
    _UpdateStatus("Skipping result prompt." & @LF)
Else
    _UpdateStatus("Prompting with results until OK clicked or " & $iResultViewTime & " seconds." & @LF)
EndIf

GUISetBkColor($shSuccessfulDoneColor, $hgNetOptStatus) ;Set to green background to indicate we are OK.
;~ MsgBox(64, "Network speed optimized.", "Your network speed has been tested.", $iResultViewTime) ;Sleep($iResultViewTime * 1000)
If $bSettingsChanged = False Then
    GUICtrlSetData($hlMainSimpleLabel, "Optimum network settings confirmed.")
    If $iResultViewTime <> -1 Then MsgBox(64, "Network optimization complete!", "Your PC has optimal network settings.", $iResultViewTime)
Else
    GUICtrlSetData($hlMainSimpleLabel, "Optimum network settings applied.")
    If $iResultViewTime <> -1 Then MsgBox(64, "Network optimization complete!", _
            "New settings were added that should give your PC better network performance.", $iResultViewTime)
EndIf
Exit ;;;;;;;;;;;;;End Script;;;;;;;;;;;;


Func _CheckForConnection($bSkipNotify = False)
    _UpdateStatus("Ensuring at least one NIC is connected. Refreshing adaptor data." & @LF)
    _GetNICStatus()
    Local $l_iPromptResult
    $bConnected = False
    For $a = 1 To $aNetworkAdaptorDetails[0][0]
        If $aNetworkAdaptorDetails[$a][18] = "Connected" Then
            $bConnected = True ;Mark that a NIC is connected.
            _UpdateStatus("NIC '" & $aNetworkAdaptorDetails[$a][2] & "' is connected." & @LF)
            Return 1
        EndIf
    Next
    ;No wired connection found if not returned by now.
    If $bSkipNotify = True Then
        _UpdateStatus("Skipping notification of missing network connection because function was called with skip flag." & @LF)
        Return -1
    EndIf
    If $iSuppressErrors = 2 Then ;If suppressing critical messages, just close the script.
        _UpdateStatus("Skipping prompt for missing wired connection and exiting because critical message reporting is disabled." & @LF)
        Exit
    EndIf
    If $bAutoStartupMode = True Then ;Suppress error if doing an auto startup check. May be using wireless or not connected but OK.
        Return -1
    EndIf

    $l_iPromptResult = _UpdateStatus("No cabled network connection found! Always use a network cable at your desk." & @LF & _
            @LF & _
            "If you are using a wireless connection or are away from the office, click cancel." & @LF & _
            @LF & _
            "If you are at your desk now, check that your network cable is connected at both ends and click 'Retry'. " & _
            "Your network cable ends will resemble a wide phone cord connection." & @LF & _
            @LF, 2, 21)
    If $l_iPromptResult = 4 Then
        _GetNICStatus() ;Refresh status so we can see if the adaptor is available now.
        _CheckForConnection()
    Else
        Exit
    EndIf
EndFunc   ;==>_CheckForConnection


Func _SetAdaptorSpeed($p_sTargetSpeed, $p_iAdaptorRow)
    Local $l_sNewNICData, $l_sFoundNicRegData, $l_sNICEnableDisableStatus
    Local $l_aNICDetails = $aNetworkAdaptorDetails[$p_iAdaptorRow][21]
    Local $l_bDisabled = False
    For $iSearchRow = 1 To $l_aNICDetails[0][0]
        ;$l_aNICDetails[0][0] = 0 ; [0][0] used for number of 1 or greater rows. Populated rows = "Reg Value"
        ;$l_aNICDetails[0][1] = "Auto Setting Data"
        ;$l_aNICDetails[0][2] = "100/Full Data"
        ;$l_aNICDetails[0][3] = "Found Speed Data"
        ;$l_aNICDetails[0][4] = "Found Actual Speed"
        _UpdateStatus("Checking for existence of '" & $aNetworkAdaptorDetails[$p_iAdaptorRow][22] & "' value '" & $l_aNICDetails[$iSearchRow][0] & "'" & @LF)
        $l_sFoundNicRegData = RegRead($aNetworkAdaptorDetails[$p_iAdaptorRow][22], $l_aNICDetails[$iSearchRow][0])
        If @error Then
            _UpdateStatus("* Not found." & @LF)
            ContinueLoop
        Else
            If $p_sTargetSpeed = "Auto" Then
                $l_sNewNICData = $l_aNICDetails[$iSearchRow][1]
            ElseIf $p_sTargetSpeed = "100/Full" Then
                $l_sNewNICData = $l_aNICDetails[$iSearchRow][2]
            Else
                _UpdateStatus("Invalid target NIC speed received. Ending script." & @LF, 2)
                Exit
            EndIf

            If $l_sFoundNicRegData = $l_sNewNICData Then
                _UpdateStatus("Data " & $p_sTargetSpeed & " already set as '" & $l_sNewNICData & "' on key key '" & _
                        $aNetworkAdaptorDetails[$p_iAdaptorRow][22] & "' with value '" & $l_aNICDetails[$iSearchRow][0] & "'. Skipping setting." & @LF)
                ContinueLoop
            EndIf

            GUICtrlSetData($hlMainSimpleLabel, "Please wait while your network card is optimized. Setting " & $p_sTargetSpeed & " speed.")

            If $l_bDisabled = False Then
                _UpdateStatus("Calling function to disable adaptor." & @LF)
                GUICtrlSetData($aNetworkAdaptorDetails[$p_iAdaptorRow][25], "Disabling adaptor so it can be set to " & $p_sTargetSpeed & "' link speed.")
                $l_sNICEnableDisableStatus = _NicEnableDisable($aNetworkAdaptorDetails[$p_iAdaptorRow][5], "Disable")
            EndIf
            If $l_sNICEnableDisableStatus <> "Disabled" Then
                GUICtrlSetData($aNetworkAdaptorDetails[$p_iAdaptorRow][25], _
                        "Error disabling adaptor! If you cannot access the network when this script is over, call the Helpdesk.")
                _UpdateStatus("Unable to disable network adaptor '" & $aNetworkAdaptorDetails[$p_iAdaptorRow][2] & "'" & @LF, 1)
                ContinueLoop ;No need to do anything else since it won't work anyway.
            Else
                $l_bDisabled = True
                _UpdateStatus("Setting " & $p_sTargetSpeed & " by adding data '" & $l_sNewNICData & "' to key '" & _
                        $aNetworkAdaptorDetails[$p_iAdaptorRow][22] & "' with value '" & $l_aNICDetails[$iSearchRow][0] & "'" & @LF)
                GUICtrlSetData($aNetworkAdaptorDetails[$p_iAdaptorRow][25], "Setting adaptor to " & $p_sTargetSpeed & " link speed.")
                $aNetworkAdaptorDetails[$p_iAdaptorRow][19] = $p_sTargetSpeed
                RegWrite($aNetworkAdaptorDetails[$p_iAdaptorRow][22], $l_aNICDetails[$iSearchRow][0], "REG_SZ", $l_sNewNICData)
                If @error Then
                    _UpdateStatus("Error '" & @error & "' setting adaptor speed in registry." & @LF, 1)
                    GUICtrlSetData($aNetworkAdaptorDetails[$p_iAdaptorRow][25], _
                            "Error setting adaptor speed! If you cannot access the network when this script is over, call the Helpdesk.")
                EndIf
            EndIf
            ;MsgBox(0, "Test", "Adaptor should be auto now but still disabled.")
        EndIf
    Next ;Check next known setting
    If $l_bDisabled = True Then
        _UpdateStatus("Re-enabling adaptor." & @LF)
        GUICtrlSetData($aNetworkAdaptorDetails[$p_iAdaptorRow][25], "Re-enabling adaptor.")
        If _NicEnableDisable($aNetworkAdaptorDetails[$p_iAdaptorRow][5], "Enable") <> "Enabled" Then
            GUICtrlSetData($aNetworkAdaptorDetails[$p_iAdaptorRow][25], _
                    "Error enabling adaptor! If you cannot access the network when this script is over, call the Helpdesk.")
            _UpdateStatus("Unable to enable network adaptor '" & $aNetworkAdaptorDetails[$p_iAdaptorRow][2] & "'" & @LF, 1)
        Else
            GUICtrlSetData($hlMainSimpleLabel, "Please wait while your network card is optimized. Waiting for connection.")
            If _IPAddressWait($p_iAdaptorRow) = 1 Then
                GUICtrlSetData($hlMainSimpleLabel, "Please wait while your network card is optimized. Connection successful.")
            EndIf
        EndIf
    EndIf
EndFunc   ;==>_SetAdaptorSpeed


Func _GetNICStatus($iDeviceID = -1)
    Local $l_iLinkSpeed, $l_iRegKeyName, $l_iColumns = 26, $l_iRow
    Local $l_bFirstRun = False, $l_bFoundAdaptor = False
    Local $l_oLinkSpeedCollection, $l_oNicsCollection, $l_oNetworkAdaptorConfig
    Local $l_sStatus, $l_sRegSpeedValue, $l_sRegAutoData, $l_sReg100FullData, $l_sNote, $l_sFoundNicSpeed
    Local $l_aNICDetails
    Dim $l_aNICDetails[1][5]

    If Not IsArray($aNetworkAdaptorDetails) Then
        $l_bFirstRun = True
        $l_iRow = 0
        Dim $aNetworkAdaptorDetails[1][$l_iColumns]
        $aNetworkAdaptorDetails[0][0] = $l_iRow
        $aNetworkAdaptorDetails[0][1] = "Starting Actual Linkspeed"
        $aNetworkAdaptorDetails[0][2] = "Description"
        $aNetworkAdaptorDetails[0][3] = "Adaptor Type"
        $aNetworkAdaptorDetails[0][4] = "Starting Status"
        $aNetworkAdaptorDetails[0][5] = "Network Connection ID"
        $aNetworkAdaptorDetails[0][6] = "Device ID"
        $aNetworkAdaptorDetails[0][7] = "Active?"
        $aNetworkAdaptorDetails[0][8] = "IP Address"
        $aNetworkAdaptorDetails[0][9] = "Gateway"
        $aNetworkAdaptorDetails[0][10] = "Starting Speed Setting"
        $aNetworkAdaptorDetails[0][11] = "MAC Address"
        $aNetworkAdaptorDetails[0][12] = "Manufacturer"
        $aNetworkAdaptorDetails[0][13] = "Product Name"
        $aNetworkAdaptorDetails[0][14] = "Instance Name"
        $aNetworkAdaptorDetails[0][15] = "Plug And Play ID"
        $aNetworkAdaptorDetails[0][16] = "Service Name"
        $aNetworkAdaptorDetails[0][17] = "Current Actual Linkspeed"
        $aNetworkAdaptorDetails[0][18] = "Current Status"
        $aNetworkAdaptorDetails[0][19] = "Current Speed Setting"
        $aNetworkAdaptorDetails[0][20] = "Note"
        $aNetworkAdaptorDetails[0][21] = "Nic Details Array"
        $aNetworkAdaptorDetails[0][22] = "Nic Full Reg Key"
        $aNetworkAdaptorDetails[0][23] = "Adaptor main line label handle"
        $aNetworkAdaptorDetails[0][24] = "Adaptor note line 1 label handle"
        $aNetworkAdaptorDetails[0][25] = "Adaptor note line 2 label handle"
    EndIf

    _UpdateStatus("Querying system for network adaptor settings and status." & @LF)
    $l_oNicsCollection = $oCIMV2.ExecQuery("SELECT * FROM Win32_NetworkAdapter") ;Get a collection of all network adaptors

    If @error Or Not IsObj($l_oNicsCollection) Then
        _UpdateStatus("Unable go get network adaptor information from system" & @LF, 1)
        Exit
    Else
        _UpdateStatus("Successfully got NIC collection." & @LF)
    EndIf

    For $oItemNics In $l_oNicsCollection
        If $iDeviceID <> -1 And $oItemNics.DeviceID <> $iDeviceID Then ContinueLoop
        If StringInStr($oItemNics.NetConnectionID, "Local Area Connection") <> 1 Then ;Look for local area connection only. Could be "Local Area Connection 1" etc.
;~          _UpdateStatus("Skipping adaptor '" & $oItemNics.Name & "' because connection ID '" & $oItemNics.NetConnectionID & _
;~                  "' does not begin with 'Local Area Connection'" & @LF)
;~          _UpdateStatus("_____________________________________________________________________" & @LF)
            ContinueLoop
        EndIf

        If StringInStr($oItemNics.Description, "VPN") Then
            _UpdateStatus("Skipping adaptor '" & $oItemNics.Name & "' because it appears to be a VPN adaptor." & @LF)
            _UpdateStatus("_____________________________________________________________________" & @LF)
            ContinueLoop
        EndIf

        If $oItemNics.NetConnectionStatus <> 2 And $oItemNics.NetConnectionStatus <> "0" And $oItemNics.NetConnectionStatus <> "7" Then
            ;Wired LAN adaptors seem to use only these three connection states.
            _UpdateStatus("Skipping adaptor '" & $oItemNics.Name & "' because status '" & $oItemNics.NetConnectionStatus & _
                    "' must be '0' (disabled), '2' (connected), or '7' (disconnected) or likely VPN adaptor or something" & @LF)
            _UpdateStatus("_____________________________________________________________________" & @LF)
            ContinueLoop
        EndIf

        ;Error: 16:56:30 Network adaptor 'VirtualBox Host-Only Ethernet Adapter' was not found in known adaptors list.
        If StringInStr($oItemNics.Description, "Virtual") Then
            _UpdateStatus("Skipping adaptor '" & $oItemNics.Name & "' because it appears to be a virtual adaptor." & @LF)
            _UpdateStatus("_____________________________________________________________________" & @LF)
            ContinueLoop
        EndIf

        If $l_bFirstRun = True Then
            ;_ArrayDisplay($aKnownAdaptorDescripts, "Known adaptor settings")
            For $i = 1 To $aKnownAdaptorDescripts[0]
                If $aKnownAdaptorDescripts[$i] <> $oItemNics.Description Then ContinueLoop
                _UpdateStatus("Matched '" & $aKnownAdaptorDescripts[$i] & "' to NIC '" & $oItemNics.Description & "' on line " & _
                        $i & " of known adaptor settings array. Getting actual settings." & @LF)
                $l_iRow += 1 ;Update the number of rows in our master array to make room for the found NIC.
                $aNetworkAdaptorDetails[0][0] = $l_iRow ;Update the array with the new number of populated rows
                ReDim $aNetworkAdaptorDetails[$l_iRow + 1][$l_iColumns] ;Add the row to the array
                If $bSimpleUI = False Then _AddNicToGUI($l_iRow) ;If we are displaying NICs, add the NIC to it.

                ReDim $l_aNICDetails[1][5] ;(Re)create temp array for NIC details.
                $l_aNICDetails[0][0] = 0 ; [0][0] used for number of 1 or greater rows. Populated rows = "Reg Value"
                $l_aNICDetails[0][1] = "Auto Setting Data"
                $l_aNICDetails[0][2] = "100/Full Data"
                $l_aNICDetails[0][3] = "Found Speed Data"
                $l_aNICDetails[0][4] = "Found Actual Speed"

                For $iNicSettingNum = 1 To 99
                    $l_sRegSpeedValue = RegRead("HKLM64\SOFTWARE\NIC Speed Optimizer\Known NICs" & "\" & _
                            $aKnownAdaptorDescripts[$i], $iNicSettingNum & ".Value")
                    If $l_sRegSpeedValue = "" Then ;Check we got a value
                        _UpdateStatus("No additional potential registry NIC settings values found." & @LF)
                        ExitLoop
                    EndIf
                    $l_sRegAutoData = RegRead("HKLM64\SOFTWARE\NIC Speed Optimizer\Known NICs" & "\" & _
                            $aKnownAdaptorDescripts[$i], $iNicSettingNum & ".Auto")
                    If $l_sRegAutoData = "" Then ;Check we got an auto setting
                        _UpdateStatus("No additional potential registry auto NIC settings found." & @LF)
                        ExitLoop
                    EndIf
                    $l_sReg100FullData = RegRead("HKLM64\SOFTWARE\NIC Speed Optimizer\Known NICs" & "\" & _
                            $aKnownAdaptorDescripts[$i], $iNicSettingNum & ".100Full")
                    If $l_sReg100FullData = "" Then ;Check we got a 100/full setting
                        _UpdateStatus("No additional potential registry 100/Full NIC settings found." & @LF)
                        ExitLoop
                    EndIf

                    _UpdateStatus("Found potential settings value " & $iNicSettingNum & ", '" & $l_sRegSpeedValue & "', which could be Auto, '" & $l_sRegAutoData & _
                            "' or 100Full, '" & $l_sReg100FullData & "'" & @LF)

                    $l_aNICDetails[0][0] += 1
                    ReDim $l_aNICDetails[$l_aNICDetails[0][0] + 1][5]
                    $l_aNICDetails[$l_aNICDetails[0][0]][0] = $l_sRegSpeedValue
                    $l_aNICDetails[$l_aNICDetails[0][0]][1] = $l_sRegAutoData
                    $l_aNICDetails[$l_aNICDetails[0][0]][2] = $l_sReg100FullData
                Next
                $aNetworkAdaptorDetails[$l_iRow][21] = $l_aNICDetails ;Save the NIC settings array to our big NICs array.
            Next ;Check for the next known adaptor for match.

            If $oItemNics.DeviceID = 0 Then
                $l_iRegKeyName = "0000"
            ElseIf $oItemNics.DeviceID > 0 And $oItemNics.DeviceID < 10 Then
                $l_iRegKeyName = "000" & $oItemNics.DeviceID
            ElseIf $oItemNics.DeviceID > 9 And $oItemNics.DeviceID < 100 Then
                $l_iRegKeyName = "00" & $oItemNics.DeviceID
            ElseIf $oItemNics.DeviceID > 99 Then
                $l_iRegKeyName = "0" & $oItemNics.DeviceID
            EndIf
            $aNetworkAdaptorDetails[$l_iRow][22] = $sRegAdaptorKeyPath & "\" & $l_iRegKeyName
        Else ;Not our first run of this function. Just get the array row number instead of creating array.
            $l_bFoundAdaptor = False
            For $r = 1 To $aNetworkAdaptorDetails[0][0]
                If $aNetworkAdaptorDetails[$r][6] = $oItemNics.DeviceID Then
                    $l_iRow = $r
                    _UpdateStatus("Updating Adaptor array row " & $l_iRow & @LF)
                    $l_bFoundAdaptor = True
                    $l_aNICDetails = $aNetworkAdaptorDetails[$l_iRow][21]
                    ExitLoop
                EndIf
            Next
            If $l_bFoundAdaptor = False Then
                _UpdateStatus("Unable to find '" & $oItemNics.Description & "'. Skipping." & @LF)
                ContinueLoop
            EndIf
        EndIf

        If Not IsArray($l_aNICDetails) Then
            _UpdateStatus("Unable to get known NICs array. Script will end." & @LF, 2)
            Exit
        EndIf

        _UpdateStatus("Searching " & $l_aNICDetails[0][0] & " known possible key(s) for adaptor speed." & @LF)
        ;_ArrayDisplay($l_aNICDetails, "Known NIC keys to search")

        $l_sFoundNicSpeed = ""
        For $iSearchRow = 1 To $l_aNICDetails[0][0]
            ;$l_aNICDetails[0][0] = 0 ; [0][0] used for number of 1 or greater rows. Populated rows = "Reg Value"
            ;$l_aNICDetails[0][1] = "Auto Setting Data"
            ;$l_aNICDetails[0][2] = "100/Full Data"
            ;$l_aNICDetails[0][3] = "Found Speed Data"
            ;$l_aNICDetails[0][4] = "Found Actual Speed"
            _UpdateStatus("Searching '" & $aNetworkAdaptorDetails[$l_iRow][22] & "' for value '" & $l_aNICDetails[$iSearchRow][0] & "'" & @LF)
            $l_aNICDetails[$iSearchRow][3] = RegRead($aNetworkAdaptorDetails[$l_iRow][22], $l_aNICDetails[$iSearchRow][0])
            If @error Then ;If $l_sFoundNicRegData = "" Then --No. Allow for blank data. Error for no key.
                _UpdateStatus("* Not found." & @LF)
                ContinueLoop
            Else
                _UpdateStatus("Found speed value " & $l_aNICDetails[$iSearchRow][3] & " in known value " & $iSearchRow & " of " & $l_aNICDetails[0][0] & @LF)
                If $l_aNICDetails[$iSearchRow][3] = $l_aNICDetails[$iSearchRow][1] Then
                    $l_aNICDetails[$iSearchRow][4] = "Auto"
                    _UpdateStatus("Network adaptor '" & $oItemNics.Description & "' Auto setting found" & @LF)
                ElseIf $l_aNICDetails[$iSearchRow][3] = $l_aNICDetails[$iSearchRow][2] Then
                    $l_aNICDetails[$iSearchRow][4] = "100Full"
                    _UpdateStatus("Network adaptor '" & $oItemNics.Description & "' 100/Full setting found" & @LF)
                Else
                    $l_aNICDetails[$iSearchRow][4] = "Unknown"
                    _UpdateStatus("Network adaptor '" & $oItemNics.Description & "' unknown setting data '" & $l_aNICDetails[$iSearchRow][3] & "' found" & @LF)
                EndIf
                If $l_sFoundNicSpeed = "" Then
                    $l_sFoundNicSpeed = $l_aNICDetails[$iSearchRow][4]
                ElseIf $l_sFoundNicSpeed = $l_aNICDetails[$iSearchRow][4] Then
                    _UpdateStatus("Multiple " & $l_aNICDetails[$iSearchRow][4] & " settings found for adaptor '" & $oItemNics.Description & _
                            "'. This can happen when driver versions are changed." & @LF)
                Else
                    _UpdateStatus("Multiple conflicting settings found for adaptor '" & $oItemNics.Description & _
                            "'. This can happen when driver versions change. Marking setting as unknown." & @LF)
                    $l_sFoundNicSpeed = "Unknown"
                EndIf
            EndIf
        Next

        If $l_sFoundNicSpeed = "" Then
            _UpdateStatus("Unable to read adaptor speed from registry." & @LF & _
                    "Contact the Helpdesk to ensure you have the best settings for your network connection!" & @LF, 1) ;Display a message for 5 minutes on error.
            Exit
        EndIf

        If $l_bFirstRun = True Then $aNetworkAdaptorDetails[0][10] = $l_sFoundNicSpeed ;"Starting Speed Setting"
        $aNetworkAdaptorDetails[0][19] = $l_sFoundNicSpeed ;"Current Speed Setting"
        $aNetworkAdaptorDetails[$l_iRow][21] = $l_aNICDetails ;Save the NIC settings array to our big NICs array.

        If $oItemNics.NetConnectionStatus = 2 Then ;If adaptor active, get IP address
            _UpdateStatus("Querying for adaptor index " & $oItemNics.DeviceID & " IP address." & @LF)
            $l_oNetworkAdaptorConfig = $oCIMV2.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index='" & $oItemNics.DeviceID & "'", "WQL", _
                    $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
            If @error Then
                _UpdateStatus("Unable go get IP Address from WMI." & @LF, 2)
                Exit
            EndIf
            For $oItemIPs In $l_oNetworkAdaptorConfig
                $aNetworkAdaptorDetails[$l_iRow][8] = $oItemIPs.IPAddress(0)
                $aNetworkAdaptorDetails[$l_iRow][9] = $oItemIPs.DefaultIPGateway(0)
            Next
        EndIf

        _UpdateStatus("Querying for adaptor speed for adaptor named '" & $oItemNics.Name & "'" & @LF)
        $l_oLinkSpeedCollection = $oWMI.ExecQuery("SELECT * FROM MSNdis_LinkSpeed WHERE InstanceName='" & $oItemNics.Name & "'", "WQL", _
                $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
        If @error Then
            _UpdateStatus("Unable go get network link speed information." & @LF, 2)
            Exit
        EndIf
        For $oItemLinkSpeed In $l_oLinkSpeedCollection
            $aNetworkAdaptorDetails[$l_iRow][7] = $oItemLinkSpeed.Active
            $aNetworkAdaptorDetails[$l_iRow][14] = String($oItemLinkSpeed.InstanceName)
            $l_iLinkSpeed = $oItemLinkSpeed.NdisLinkSpeed
            $l_iLinkSpeed = $l_iLinkSpeed / 10000
        Next
        $aNetworkAdaptorDetails[$l_iRow][0] = $oItemNics.Name
        _UpdateStatus("_____________________________________________________________________" & @LF)
        _UpdateStatus("Updating details for network adaptor " & $l_iRow & " named '" & $aNetworkAdaptorDetails[$l_iRow][0] & _
                "' with linkspeed '" & $l_iLinkSpeed & "' Mbps" & @LF)
        $aNetworkAdaptorDetails[$l_iRow][3] = $oItemNics.AdapterType
        $aNetworkAdaptorDetails[$l_iRow][2] = $oItemNics.Description
        $aNetworkAdaptorDetails[$l_iRow][6] = $oItemNics.DeviceID
;~      $sCMV2LinkSpeed = $oItemNics.Speed ;Doesn't work with XP
        $aNetworkAdaptorDetails[$l_iRow][11] = $oItemNics.MACAddress
        $aNetworkAdaptorDetails[$l_iRow][12] = $oItemNics.Manufacturer
        $aNetworkAdaptorDetails[$l_iRow][5] = $oItemNics.NetConnectionID
        If $oItemNics.NetConnectionStatus = 0 Then
            $l_sStatus = "Disabled"
        ElseIf $oItemNics.NetConnectionStatus = 2 Then
            $l_sStatus = "Connected"
        ElseIf $oItemNics.NetConnectionStatus = 7 Then
            $l_sStatus = "Disconnected"
        Else
            $l_sStatus = "Unrecognized"
        EndIf
        GUICtrlSetData($aNetworkAdaptorDetails[$l_iRow][23], $oItemNics.NetConnectionID & ": " & $oItemNics.Description)
        $aNetworkAdaptorDetails[$l_iRow][13] = $oItemNics.ProductName
        $aNetworkAdaptorDetails[$l_iRow][15] = $oItemNics.PNPDeviceID
        $aNetworkAdaptorDetails[$l_iRow][16] = $oItemNics.ServiceName
        $aNetworkAdaptorDetails[$l_iRow][17] = $l_iLinkSpeed
        $aNetworkAdaptorDetails[$l_iRow][18] = $l_sStatus
        $aNetworkAdaptorDetails[$l_iRow][19] = $l_sFoundNicSpeed

        If $l_bFirstRun = True Then
            $aNetworkAdaptorDetails[$l_iRow][1] = $l_iLinkSpeed
            $aNetworkAdaptorDetails[$l_iRow][4] = $l_sStatus
            $aNetworkAdaptorDetails[$l_iRow][10] = $l_sFoundNicSpeed
            GUICtrlSetData($aNetworkAdaptorDetails[$l_iRow][24], "Original speed setting: " & $l_sFoundNicSpeed & ", actual linkspeed: " & $l_iLinkSpeed)
            _UpdateStatus("Network Connection ID '" & $aNetworkAdaptorDetails[$l_iRow][5] & "' details:" & @LF & _ ;"Name: '" & $sName & "'" & @LF & _
                    "         Status: '" & $aNetworkAdaptorDetails[$l_iRow][4] & "'" & @LF & _
                    "         Active: '" & $aNetworkAdaptorDetails[$l_iRow][7] & "'" & @LF & _
                    "         Linkspeed: '" & $aNetworkAdaptorDetails[$l_iRow][1] & "' Mbps" & @LF & _
                    "         Speed/Duplex Setting: '" & $l_sFoundNicSpeed & "'" & @LF & _
                    "         IP address: '" & $aNetworkAdaptorDetails[$l_iRow][8] & "'" & @LF & _
                    "         Gateway '" & $aNetworkAdaptorDetails[$l_iRow][9] & "'" & @LF & _ ;"         Adaptor Type '" & $aNetworkAdaptorDetails[$l_iRow][3] & "'" & @LF & _
                    "         Description '" & $aNetworkAdaptorDetails[$l_iRow][2] & "'" & @LF & _
                    "         Device ID: '" & $aNetworkAdaptorDetails[$l_iRow][6] & "'" & @LF & _
                    "         MAC Address '" & $aNetworkAdaptorDetails[$l_iRow][11] & "'" & @LF & _
                    "         Manufacturer '" & $aNetworkAdaptorDetails[$l_iRow][12] & "'" & @LF & _
                    "         Plug And Play ID '" & $aNetworkAdaptorDetails[$l_iRow][15] & "'" & @LF & _
                    "         Product Name '" & $aNetworkAdaptorDetails[$l_iRow][13] & "'" & @LF & _
                    "         Service Name '" & $aNetworkAdaptorDetails[$l_iRow][16] & "'" & @LF)
            _UpdateStatus("_____________________________________________________________________" & @LF)
        Else
            If $aNetworkAdaptorDetails[$r][17] <> $aNetworkAdaptorDetails[$l_iRow][1] Then ;Linkspeed changed
                $l_sNote = "Speed changed to '" & $aNetworkAdaptorDetails[$l_iRow][17] & _
                        "' from original '" & $aNetworkAdaptorDetails[$l_iRow][1] & "'"
            EndIf
            If $aNetworkAdaptorDetails[$l_iRow][19] <> $aNetworkAdaptorDetails[$l_iRow][10] Then ;Adaptor registry setting changed
                If $l_sNote = "" Then
                    $l_sNote = "Adaptor setting changed to '" & $aNetworkAdaptorDetails[$l_iRow][19] & _
                            "' from original '" & $aNetworkAdaptorDetails[$l_iRow][10] & "'"
                Else
                    $l_sNote = $l_sNote & ", Adaptor setting changed to '" & $aNetworkAdaptorDetails[$l_iRow][19] & _
                            "' from original '" & $aNetworkAdaptorDetails[$l_iRow][10] & "'"
                EndIf
            EndIf
            If $l_sNote = "" Then $l_sNote = "Unchanged"
            $aNetworkAdaptorDetails[$l_iRow][20] = $l_sNote
            _UpdateStatus("New status is '" & $aNetworkAdaptorDetails[$l_iRow][20] & "'" & @LF)
            ;_UpdateStatus("_____________________________________________________________________" & @LF)
            GUICtrlSetData($aNetworkAdaptorDetails[$l_iRow][25], "Final result: " & $l_sNote)
        EndIf
    Next ;Next WMI adaptor
    $aNetworkAdaptorDetails[0][0] = $l_iRow
EndFunc   ;==>_GetNICStatus


Func _IPAddressWait($l_iRow)
    Local $l_iResult
    _UpdateStatus("Waiting up to 2 minutes for an IP address." & @LF)
    GUICtrlSetData($aNetworkAdaptorDetails[$l_iRow][25], "Set to " & $aNetworkAdaptorDetails[$l_iRow][19] & ". Waiting up to 2 minutes for an IP address.")
    For $c = 1 To 24
        If $c > 1 Then Sleep(5000) ;Wait 5 seconds
        $l_oNetworkAdaptorConfig = $oCIMV2.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index='" & _
                $aNetworkAdaptorDetails[$l_iRow][6] & "'", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
        If @error Then
            GUICtrlSetData($aNetworkAdaptorDetails[$l_iRow][25], "Error. Unable to get IP address from WMI!")
            _UpdateStatus("Unable go get IP Address from WMI." & @LF, 1)
            Exit
        EndIf
        For $oItemIPs In $l_oNetworkAdaptorConfig
            If StringStripWS($oItemIPs.DefaultIPGateway(0), 8) <> "" Then ;Nothing prints to screen, but "" does not work. Strip non-printing.
                $aNetworkAdaptorDetails[$l_iRow][8] = $oItemIPs.IPAddress(0)
                $aNetworkAdaptorDetails[$l_iRow][9] = $oItemIPs.DefaultIPGateway(0)
                _UpdateStatus("Got IP address of '" & $aNetworkAdaptorDetails[$l_iRow][8] & "' with gateway '" & _
                        $aNetworkAdaptorDetails[$l_iRow][9] & "'" & @LF)
                GUICtrlSetData($aNetworkAdaptorDetails[$l_iRow][25], "Got IP address of '" & $aNetworkAdaptorDetails[$l_iRow][8] & "'")
                Return 1
            EndIf
        Next ;Done getting settings from collection
    Next ;Try again
    If StringStripWS($oItemIPs.DefaultIPGateway(0), 8) = "" Then ;Nothing prints to screen, but "" does not work. Strip non-printing characters.
        $l_iResult = _CheckForConnection() ;Check if we are connected on a different NIC
        If $l_iResult = 4 Then ;No connection but user said retry
            _IPAddressWait($l_iRow)
        ElseIf $l_iResult = 1 Then ;A connection has been found, but no IP address?
            _UpdateStatus("Unable to get IP address." & @LF, 1)
            GUICtrlSetData($aNetworkAdaptorDetails[$l_iRow][25], "Error. Unable to get IP address!")
            Return -1
        EndIf
    EndIf ;Done with error not getting IP address
EndFunc   ;==>_IPAddressWait


Func _AddNicToGUI($iNicLine)
    Local $l_iNoteLine1Vpos = $iGuiVPos
    Local $l_iNoteLine2Vpos = $l_iNoteLine1Vpos + $iGuiMedLabelHeight
    Local $l_iNoteLine3Vpos = $l_iNoteLine2Vpos + $iGuiSmallLabelHeight
    Local $l_iDetailsVPos = $l_iNoteLine3Vpos + $iGuiSmallLabelHeight
    $iGuiVPos = $l_iDetailsVPos
    $iGuiHeight = $l_iDetailsVPos + $iGuiDetailHeight + 30 ;Kluge +30 to account for top modal frame bar

    _UpdateStatus("Making room in the GUI for adaptor." & @LF)
    WinMove($hgNetOptStatus, "", Default, Default, Default, $iGuiHeight)
    GUICtrlSetPos($heGuiDetails, 0, $l_iDetailsVPos)

    $aNetworkAdaptorDetails[$iNicLine][23] = GUICtrlCreateLabel("", $iGuiHBufferSpace, $l_iNoteLine1Vpos, $iLabelWidth, $iGuiMedLabelHeight, $SS_CENTER);"Adaptor main line label handle"
    GUICtrlSetFont($aNetworkAdaptorDetails[$iNicLine][23], $iMedFontSize, 800)
    GUICtrlSetResizing($aNetworkAdaptorDetails[$iNicLine][23], $GUI_DOCKALL)

    $aNetworkAdaptorDetails[$iNicLine][24] = GUICtrlCreateLabel("", $iGuiHBufferSpace, $l_iNoteLine2Vpos, $iLabelWidth, $iGuiSmallLabelHeight, $SS_CENTER) ;"Adaptor note line 1 label handle"
    GUICtrlSetFont($aNetworkAdaptorDetails[$iNicLine][24], $iSmallFontSize, 400)
    GUICtrlSetResizing($aNetworkAdaptorDetails[$iNicLine][24], $GUI_DOCKALL)

    $aNetworkAdaptorDetails[$iNicLine][25] = GUICtrlCreateLabel("Waiting to test speed.", _
            $iGuiHBufferSpace, $l_iNoteLine3Vpos, $iLabelWidth, $iGuiSmallLabelHeight, $SS_CENTER) ;Adaptor note line 2 label handle"
    GUICtrlSetFont($aNetworkAdaptorDetails[$iNicLine][25], $iSmallFontSize, 400)
    GUICtrlSetResizing($aNetworkAdaptorDetails[$iNicLine][25], $GUI_DOCKALL)
    ;_ArrayDisplay($aNetworkAdaptorDetails, "After adding handles to columns 26-18")
EndFunc   ;==>_AddNicToGUI


Func _UpdateStatus($p_sStatusLines, $p_iError = 0, $p_iMessageBox = 16)
    Local $l_iPromptResult = 1
    Local $l_sErrorText, $l_sModifiedStatusLines = @HOUR & ":" & @MIN & ":" & @SEC & " " & StringReplace($p_sStatusLines, @LF, @CRLF)

    If $p_iError Then
        If $p_iError = 1 Then
            $l_sModifiedStatusLines = "Error: " & $l_sModifiedStatusLines
        ElseIf $p_iError = 2 Then
            $l_sModifiedStatusLines = "Critical Error! " & $l_sModifiedStatusLines
        EndIf
        RegWrite("HKLM64\SOFTWARE\NIC Speed Optimizer", "Last Error", "Reg_SZ", @MON & "/" & @MDAY & "/" & @YEAR & " " & StringReplace($l_sModifiedStatusLines, @CRLF, " "))
        $l_sErrorText = StringReplace($l_sModifiedStatusLines, @CRLF, " ") & @LF
        If $sFinalNote = "" Then
            $sFinalNote = $l_sErrorText
        Else
            $sFinalNote = $sFinalNote & "; " & $l_sErrorText
        EndIf
;~      If $l_sNicReg <> "" Then $l_sErrorText = $l_sNicReg & " ;" & $l_sErrorText
;~      RegWrite($sRegStatusPath, "Nic Optimized As", "Reg_SZ", $l_sErrorText)
    EndIf
    If $bSimpleUI = False Then _GUICtrlEdit_AppendText($heGuiDetails, $l_sModifiedStatusLines)
    FileWriteLine($hfLog, $l_sModifiedStatusLines)
    If $p_iError = 1 Then
;~      FileWriteLine($hfLog, "Error: " & @HOUR & ":" & @MIN & ":" & @SEC & " " & $p_sStatusLines)
        If $iSuppressErrors < 1 Then
            GUISetBkColor($shErrorColor, $hgNetOptStatus)
            GUICtrlSetData($hlMainSimpleLabel, $p_sStatusLines)
            $l_iPromptResult = MsgBox($p_iMessageBox, "Error", $p_sStatusLines & @LF & "If you cannot access the network after this script is done," & @LF & _
                    "Please contact the Helpdesk!", $iTimeoutStandardError)
        Else
            _UpdateStatus("Skipping standard error message." & @LF)
        EndIf
    ElseIf $p_iError = 2 Then
;~      FileWriteLine($hfLog, "Critical Error! " & @HOUR & ":" & @MIN & ":" & @SEC & " " & $p_sStatusLines)
        If $iSuppressErrors <> 2 Then
            GUISetBkColor($shErrorColor, $hgNetOptStatus)
            GUICtrlSetData($hlMainSimpleLabel, $p_sStatusLines)
            $l_iPromptResult = MsgBox($p_iMessageBox, "Critical Error!", $p_sStatusLines & @LF & "If you cannot access the network after this script is done," & @LF & _
                    "Please contact the Helpdesk!", $iTimeoutCriticalError)
        Else
            _UpdateStatus("Skipping critical error prompt." & @LF)
        EndIf
    Else
;~      FileWriteLine($hfLog, @HOUR & ":" & @MIN & ":" & @SEC & " " & $p_sStatusLines)
        GUISetBkColor($shNormalColor, $hgNetOptStatus)
    EndIf
    Return $l_iPromptResult
;~  EndIf
EndFunc   ;==>_UpdateStatus


Func _NicEnableDisable($sLANConnectionName = "Local Area Connection", $sEnableDisableView = "View", $iTimOutSecs = 30)
    Local $l_sResult ;, $iFlag
    Local $l_oNicsCollection
    Local $l_sCurrentStatus

    If @OSVersion = "WIN_XP" Then
        _UpdateStatus("Calling legacy XP NIC function." & @LF)
        $l_sResult = _NicEnableDisableXP($sLANConnectionName, $sEnableDisableView, $iTimOutSecs)
        If $sEnableDisableView = "Disable" Then
            _KillNetError()
        EndIf
        Return $l_sResult
    EndIf

    _UpdateStatus("Getting NIC collection so we can do action '" & $sEnableDisableView & "' on connection '" & $sLANConnectionName & "'" & @LF)
    $l_oNicsCollection = $oCIMV2.ExecQuery("SELECT * FROM Win32_NetworkAdapter", "WQL", 0x30) ;Get a collection of all network adaptors
;~  $l_oNicsCollection = $oCIMV2.ExecQuery("SELECT * FROM Win32_NetworkAdapter") ;Get a collection of all network adaptors

    If @error Then
        _UpdateStatus("NIC optimization error!: Unable to get network adaptor information." & @LF, 1)
        Exit
    Else
        _UpdateStatus("Parsing collection for target device." & @LF)
    EndIf

    For $oItemNics In $l_oNicsCollection
        If $oItemNics.NetConnectionID <> $sLANConnectionName Then
            ContinueLoop
;~      Else
;~          _UpdateStatus("Proccesing connection " & $oItemNics.NetConnectionID & @LF)
        EndIf

        If $oItemNics.NetEnabled = True Then
            $l_sCurrentStatus = "Enabled"
        Else
            $l_sCurrentStatus = "Disabled"
        EndIf

        _UpdateStatus($oItemNics.NetConnectionID & " is currently " & $l_sCurrentStatus & "." & @LF)

        If $sEnableDisableView = "View" Then
;~          _UpdateStatus("Adaptor is currently " & $l_sCurrentStatus & "." & @LF)
        Else
            If $sEnableDisableView = "Disable" Then
;~              _UpdateStatus("Checking NetEnabled status for adaptor." & @LF)
                If $oItemNics.NetEnabled = True Then
                    _UpdateStatus("Disabling adaptor." & @LF)
                    _LANDeskInvCheck()
                    $oItemNics.Disable
                Else
                    _UpdateStatus("Adaptor is already disabled" & @LF)
                    _KillNetError()
                    Return "Disabled"
                EndIf
            ElseIf $sEnableDisableView = "Enable" Then
                If $oItemNics.NetEnabled = False Then
                    _UpdateStatus("Enabling adaptor." & @LF)
                    $oItemNics.Enable
                Else
                    _UpdateStatus("Adaptor is already enabled." & @LF)
                    Return "Enabled"
                EndIf
            EndIf
            For $i = 1 To $iTimOutSecs
;~              If $sEnableDisableView = "Disable" And $oItemNics.NetEnabled = False Then ;Not dynamic. Must rerun function from beginning.
                If $sEnableDisableView = "Disable" And _NicEnableDisable($sLANConnectionName, "View") = "Disabled" Then
                    _UpdateStatus("Adaptor successfully disabled." & @LF)
                    _KillNetError()
                    Return "Disabled"
;~              ElseIf $sEnableDisableView = "Enable" And $oItemNics.NetEnabled = True Then ;Not dynamic. Must rerun function from beginning.
                ElseIf $sEnableDisableView = "Enable" And _NicEnableDisable($sLANConnectionName, "View") = "Enabled" Then
                    _UpdateStatus("Adaptor successfully enabled." & @LF)
                    Return "Enabled"
                Else
                    If $i = 1 Then _UpdateStatus("Waiting up to " & $iTimOutSecs & " seconds for adaptor to " & $sEnableDisableView & @LF)
                    Sleep(1000)
                EndIf
            Next
        EndIf
        ExitLoop
    Next
EndFunc   ;==>_NicEnableDisable


Func _NicEnableDisableXP($sLANConnectionName = "Local Area Connection", $sEnableDisableView = "View", $iTimOutSecs = 30) ;, $iFullName = 1)
    ;Adapted from http://www.autoitscript.com/forum/index.php?showtopic=12645&view=findpost&p=87000
    ;Original author : SvenP
    Local $l_oLanConnection, $l_oEnableVerb, $l_oDisableVerb, $l_oNetConnections
    Local $l_sCurrentStatus

    $ShellApp = ObjCreate("Shell.Application")
    $oControlPanel = $ShellApp.Namespace(3)

    For $FolderItem In $oControlPanel.Items ;Find 'Network connections' control panel item
        If $FolderItem.Name = $sNetConnectionSystemName Then
            $l_oNetConnections = $FolderItem.GetFolder
            ExitLoop
        EndIf
    Next

    If Not IsObj($l_oNetConnections) Then ;If no 'Network connections' folder then return error.
        SetError(1, 2)
        Return 0
    EndIf

    For $FolderItem In $l_oNetConnections.Items ;Find the collection of the network connection name.
        If StringLower($FolderItem.Name) = StringLower($sLANConnectionName) Then
            $l_oLanConnection = $FolderItem
            ExitLoop
        EndIf
    Next

    If Not IsObj($l_oLanConnection) Then ;If no network connection name then return error.
        SetError(1, 3)
        Return 0
    EndIf

    For $Verb In $l_oLanConnection.Verbs ;Find the state of the network connection.
        If $Verb.Name = $sEnableVerb Then
            $l_oEnableVerb = $Verb
            $l_sCurrentStatus = "Disabled"
        EndIf
        If $Verb.Name = $sDisableVerb Then
            $l_oDisableVerb = $Verb
            $l_sCurrentStatus = "Enabled"
        EndIf
    Next

    _UpdateStatus("Current status is " & $l_sCurrentStatus & @LF)

    If $sEnableDisableView = "View" Then
        If $l_sCurrentStatus <> "" Then
;~          _UpdateStatus("Current status is " & $l_sCurrentStatus & @LF)
            Return $l_sCurrentStatus
        Else
            _UpdateStatus("Error getting adaptor status." & @LF)
            Return "Error"
        EndIf
    ElseIf $sEnableDisableView = "Enable" Then
        If $l_sCurrentStatus = "Enabled" Then
            _UpdateStatus("Adaptor already enabled." & @LF)
            Return "Enabled"
        ElseIf IsObj($l_oEnableVerb) Then
            _UpdateStatus("Enabling adaptor." & @LF)
            $l_oEnableVerb.DoIt
        Else
            _UpdateStatus("Error communicationg with adaptor" & @LF)
            Return "Error"
        EndIf
    ElseIf $sEnableDisableView = "Disable" Then
        If $l_sCurrentStatus = "Disabled" Then
            _UpdateStatus("Adaptor already disabled." & @LF)
            Return "Disabled"
        ElseIf IsObj($l_oDisableVerb) Then
            _LANDeskInvCheck()
            _UpdateStatus("Disabling adaptor." & @LF)
            $l_oDisableVerb.DoIt
        Else
            _UpdateStatus("Error communicationg with adaptor" & @LF)
            Return "Error"
        EndIf
    EndIf

    If $sEnableDisableView = "Enable" Then
        For $w = 1 To $aNetworkAdaptorDetails[0][0]
            If $aNetworkAdaptorDetails[$w][5] = $sLANConnectionName Then
                _UpdateStatus("Calling IP address wait function." & @LF)
                GUICtrlSetData($hlMainSimpleLabel, "Please wait while your network card is optimized. Waiting for connection.")
                If _IPAddressWait($a) = 1 Then
                    GUICtrlSetData($hlMainSimpleLabel, "Please wait while your network card is optimized. Connection successful.")
                    Return "Enabled"
                EndIf
            EndIf
        Next
    Else
        For $i = 1 To $iTimOutSecs ;Wait for action to complete
            For $Verb In $l_oLanConnection.Verbs
                If $Verb.Name = $sEnableVerb Then
                    _UpdateStatus("Adaptor disabled." & @LF)
                    Return "Disabled"
                EndIf
            Next
            If $i = 1 Then _UpdateStatus("Waiting up to " & $iTimOutSecs & " seconds for adaptor to " & $sEnableDisableView & @LF)
            Sleep(1000)
        Next
    EndIf

    _UpdateStatus("Error setting adaptor to state " & $sEnableDisableView & @LF)
    Return $l_sCurrentStatus
EndFunc   ;==>_NicEnableDisableXP


Func _LANDeskInvCheck()
;~  Local $l_iWaitMinutes = 10 ;Check every half second for 10 minutes (10 * 60 seconds * 1000 milliseconds)
;~  Local $l_iWaitMilliseconds = $l_iWaitMinutes * 60 * 1000
    If Not ProcessExists("LDISCN32.EXE") Then
        _UpdateStatus("LANDesk Inventory Scan not running. Safe to disable NIC." & @LF)
        Return 1
    EndIf
    $bRunLANDeskOnEnd = True
    _UpdateStatus("Closing LANDesk Inventory Scan process so NIC can be disabled. Scan will be restarted after script runs." & @LF)
    ProcessClose("LDISCN32.EXE")
    Return 2
;~  _UpdateStatus("Waiting up to " & $l_iWaitMinutes & " minutes, or " & $l_iWaitMilliseconds & " milliseconds for LANDesk Inventory Scan to complete." & @LF)
;~  _UpdateStatus("Cannot disable NIC while LANDesk is communicating with core server." & @LF)
;~  For $i = 1 To $l_iWaitMilliseconds * 2 ;Check every half second for 10 minutes (loop milliseconds * 2)
;~      If ProcessExists("LDISCN32.EXE") Then
;~          ;_UpdateStatus("Still exists as PID " & ProcessExists("cmd.exe") & @LF)
;~          Sleep(500)
;~      Else
;~          Return 1
;~      EndIf
;~  Next
EndFunc   ;==>_LANDeskInvCheck


Func _KillNetError()
    For $e = 1 To 30
        If WinActivate("Location is not available") Then
            _UpdateStatus("Attempting to kill 'Location is not available' prompt." & @LF)
            WinWaitActive("Location is not available", "", 5)
            If WinActive("Location is not available") Then Send("{ALTUP}{ENTER}")
        Else
            _UpdateStatus("'Location is not available' prompt not found. exiting kill loop line " & $e & "." & @LF)
            ExitLoop ;;;;;;;;;;;;;End Script;;;;;;;;;;;;
        EndIf
    Next

EndFunc   ;==>_KillNetError


Func _ComErrorHandler($oError)
    _UpdateStatus("Com error. Details:" & @LF & _
            "Error number: " & $oError.number & @LF & _
            "Windows error description: " & $oError.windescription & @LF & _
            "Description: " & $oError.description & @LF & _
            "Error source: " & $oError.source & @LF & _
            "Error helpfile: " & $oError.helpfile & @LF & _
            "Error help context: " & $oError.helpcontext & @LF & _
            "Last dll error: " & $oError.lastdllerror & @LF & _
            "Script line: " & $oError.scriptline & @LF & _
            "Return code: " & $oError.retcode & @LF, 2)
    Exit
EndFunc   ;==>_ComErrorHandler


Func _EndScriptCleanUp()
    Local $l_sLanDeskCommand, $l_sLandeskCmdKey, $l_sLandeskCmdValue
    If $bRunLANDeskOnEnd = True Then
        $l_sLandeskCmdKey = "HKLM64\Software\NIC Speed Optimizer"
        $l_sLandeskCmdValue = "LANDesk Inventory Command"
        _UpdateStatus("Looking for LANDesk run key in key '" & $l_sLandeskCmdKey & "' with value '" & $l_sLandeskCmdValue & "'" & @LF)
        $l_sLanDeskCommand = RegRead($l_sLandeskCmdKey, $l_sLandeskCmdValue)
        If $l_sLanDeskCommand <> "" Then
            _UpdateStatus("Running LANDesk inventory scan with command '" & $l_sLanDeskCommand & "'" & @LF)
            Run($l_sLanDeskCommand)
        Else
            _UpdateStatus("Unable to get LANDesk inventory run command. Skipping inventory scan." & @LF)
        EndIf
    EndIf
    FileClose($hfLog)
EndFunc   ;==>_EndScriptCleanUp

NIC Speed Optimizer.7z

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×