'***************************************************************************************************************
'*                                    INTEL DISCLOSURE And COPYRIGHT INFORMATION                              '*
'*                                                                                                            '*  
'*                THIS DOCUMENT AND ALL INFORMATION PROVIDED HEREIN, INCLUDING CODE, IS PROVIDED              '*  
'*                "AS IS" WITH NO WARRANTIES WHATSOEVER, INCLUDING ANY WARRANTY OF MERCHANTABILITY,           '*
'*                NONINFRINGEMENT, FITNESS FOR ANY PARTICULAR PURPOSE, OR ANY WARRANTY OTHERWISE              '* 
'*                ARISING OUT OF ANY PROPOSAL, SPECIFICATION OR SAMPLE.                                       '*
'*                Intel disclaims all liability, including liability for infringement of any proprietary      '*
'*                rights, relating to use of information or code in this document.   Recipient may use        '*
'*                this document and all information herein, including code, but all such use is and shall     '*
'*                be at recipient's sole risk and subject to the disclaimers and limitations of liability     '*
'*                herein.  No other license, express or implied, by estoppel or otherwise, to any             '*  
'*                intellectual property rights is granted herein.                                             '*  
'*                Copyright (c) Intel Corporation 2008. *Third-party brands and names are                     '*  
'*                the property of their respective owners.                                                    '*  
                                                                                                       
'***************************************************************************************************************

' File               :     VBSLIB.VBS
' Version           :     1.0
'
'
'  Instructions for use:
'  =====================
'  1) Add Include("VBSLIB.vbs") to the top of the script
'  2) Place the following Function in script:
'
'    Function Include(vbsFile)
'
'     dim fso, ts, buf, path
'      
'     Set fso = CreateObject("Scripting.FileSystemObject")
'      
'     path = fso.GetParentFolderName (WScript.ScriptFullName) & "\" & vbsFile
'      
'     If fso.FileExists(path) Then  
'          set ts = fso.OpenTextFile(path)
'          buf = ts.ReadAll()
'           ts.Close()
'           Executeglobal buf
'     Else
'          Wscript.Echo "Unable to open include file: " & path
'     End If
'     
'   End Function
'
'******************************************************************************
option explicit
'===================================================
'  Script Constants
'===================================================
   Const HKEY_LOCAL_MACHINE = &H80000002
   Const wbemFlagUseAmEndedQualIfiers = &h20000
   Const wbemFlagReturnImmediately = 16
   Const wbemChangeFlagCreateOnly = &h2
   Const wbemChangeFlagCreateOrUpdate = &h0
   Const WbemAuthenticationLevelPktPrivacy = 6
   Const wbemImpersonationLevelImpersonate = 3


   Const THIRD_PARTY_ADAPTER = 0
   Const INTEL_ADAPTER = 1
   Const NOT_AN_ADAPTER = 2

   Const CMD_START = 0
   Const CMD_CANCEL = 1
   Const CMD_RESULTS = 2

   Const TEAMING_IS_TEAMABLE = 36
   Const TEAMING_MODE_AFT = 4
   Const TEAMING_MODE_ALB = 5
   Const TEAMING_MODE_GEC = 8
   Const TEAMING_MODE_FEC = 9
   Const TEAMING_MODE_8023AD = 10
   Const TEAMING_MODE_SFT = 12
   Const TEAMING_MODE_VMLB = 68

   const LSO_IPv6_WARNING = &h0002
   const LSO_IPv4_WARNING = &h0004
   const LSO_DISABLED_WARNING = &h0008
   
   Const DEBUG_MODE = True

   dim AdapterIndexString 
   AdapterIndexString      =  "AdapterIndex - Specifies the adapter." & VbNewLine &_
   			      "		   The Index is the adapter number generated." 
                                                                    
   dim AdapterListString                            
   AdapterListString         = "AdapterList  - Comma delimited list of adapter indices (ie 1,2,3)" & VbNewLine
   
   dim AdapterGetIndexString     
   AdapterGetIndexString     = "The AdapterIndex is obtained by running the " & VbNewLine &_
   			       "           	   Adapter_Enumerate script on the system"& VbNewLine 
   			       
   dim SettingNameString
   SettingNameString         = "SettingName  - Specifies the name of the Setting (Adapter or Team)" & VbNewLine 
   
   dim SettingValueString
   SettingValueString        = "SettingValue - Specifies the configuration value of the setting " & VbNewLine &_
   				     " 		   (Adapter or Team) you wish to change" & VbNewLine 
   				     
   dim TeamIndexString
   TeamIndexString           = "TeamIndex    - Specifies the team." & VbNewLine &_
   			       "		   The Index is the team number generated" 
   
   dim TeamGetIndexString
   TeamGetIndexString        = "The TeamIndex is obtained by running the " & VbNewLine &_
   			       "		   Team_Enumerate script on the system" & VbNewLine  		   
   
   
   dim VlanIdString
   VlanIdString              = "VlanID     	 - Assigns a number to the VLAN." 
   			       
   dim VlanIdGetString
   VlanIdGetString           = "VlanID     	 - ID of the VLAN to use."    
   
   dim OptionalCmdLineArgsString
   OptionalCmdLineArgsString  =  "  Optional: " & VbNewLine &_
                               "    Help     - Describes the script's arguments" & VbNewLine & VbNewLine &_
                               "    Target   - Specifies the computer receiving the request." & VbNewLine &_
                               "               A <username>  and <password> are required for the target" & VbNewLine &_
                               "	       computer. If a target computer is not specified, the script"& VbNewLine &_
                               "               is run on the local computer" & VbNewLine  & VbNewLine &_
                               "    Username - Specifies the Username on the target system " & VbNewLine &_
                               "               For no Username, type """"" & VbNewLine  & VbNewLine &_
                               "    Password - Specifies the Password on the target system " & VbNewLine &_
                               "               For no Password, type  """""& VbNewLine & VbNewLine &_
                               "    Note:  Omitting the target/username/password " & VbNewLine &_
                               "           values will default to local execution"

' Put commands that all scripts must execute here

     ' Check to make sure the script was run using CSCRIPT.
     ' If it wasn't, tell the user to use CSCRIPT and exit the script
     if not IsCScript() then
          wscript.echo "WSCRIPT.exe execution is not supported.  Please use CSCRIPT.exe"
          wscript.quit 0
     end if
     
'===================================================
'  Function : WMIConnect
'   Purpose : Establishes a connection to a namespace with supplied credentials
' Arguments :  1. a variable to receive a SwbemServices object
'              2. the name of the namespace to connect
'                         3. the address of the target
'              4. the user name to supply the connection request
'              5. the password to supply the connection request
'              6. sReturn (string) - if the function returns fail, this will contain the reason
'   Returns : True (if connection was successful); or false
'     Notes : 
'              User name can be in the form of either a user name or a Domain\Username
'===================================================
     Function WMIConnect (byref hWMIService, byval sNamespace, byval sAddress, byval sUsername, byval sPassword, byref sReturn)
     
          Err.Clear
          On Error Resume Next
          
          Dim objSWbemLocator
          Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")

          Set hWMIService = objSWbemLocator.ConnectServer(sAddress, sNamespace, sUsername, sPassword) 
          
          'Determine whether an error was thrown and set return value
          If IsEmpty(hWMIService) or IsNull(hWMIService) Then
               sReturn = "Unable to establish connection to " & sNamespace & GetErr
               WMIConnect = False
          Else
               
               'Set permissions; this is recommended for WMI connections
               hWMIService.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate
               
               'Encrypt communication between client and server; if not required, this setting is ignored
               hWMIService.Security_.authenticationLevel = WbemAuthenticationLevelPktPrivacy
               
               'Required for some administrative tasks
               hWMIService.Security_.Privileges.AddAsString "SeLoadDriverPrivilege"
               
                 WMIConnect = True
            End If
     
     End Function

     '===================================================
     '  Function : SelectQueryWmiClass
     '  Purpose : Executes a SELECT/FROM WMI query and returns the object to the caller
     '  Arguments : hWMIService - WMI handle to execute the the query on
     '              sColumn     - Column to retreive in the query (can be * to get all)
     '              sClass      - WMI Class to query
     '              sWhere      - Conditions on what is returned
     '                     
     '   Returns : Nothing
     '     Notes : The array that is passed in must be a dynamic size
     '===================================================
     Function SelectQueryWmiClass(byRef hWMIService, byVal sColumn, byVal sClass, byVal sWhere)
          if IsObject(hWMIService) then
               dim WQL : WQL = "SELECT " & sColumn & " FROM " & sClass
               if Len(sWhere) > 0 then
                    WQL = WQL & " WHERE " & sWhere
               end if
               dim QueryResults : Set QueryResults = hWMIService.ExecQuery(WQL)

               if not IsNull(QueryResults) then
                    set SelectQueryWmiClass = QueryResults
               else 
                    set SelectQueryWmiClass = nothing
               end if
               
         end if
     End function

     '===================================================
     '  Function : AssociatorsOfQueryWmiClass
     '  Purpose   : Executes a ASSOCIATORS OF WMI query and returns the object to the caller
     '  Arguments : hWMIService - WMI handle to execute the the query on
     '              hValueSet   - Value set to be used when executing the query
     '              sDevicePath - Path to the device to get the associators of
     '              sWhere      - Conditions on what is returned
     '                     
     '   Returns : Nothing
     '     Notes : The array that is passed in must be a dynamic size
     '===================================================
     Function AssociatorsOfQueryWmiClass(byRef hWMIService, byRef hValueSet, byVal sDevicePath, byVal sWhere)
          if IsObject(hWMIService) then
               dim WQL : WQL = "ASSOCIATORS OF {" & sDevicePath & "}"
               if Len(sWhere) > 0 then
                    WQL = WQL & " WHERE " & sWhere
               end if
               dim QueryResults : Set QueryResults = hWMIService.ExecQuery(WQL,,,hValueSet)

               if not IsNothing(QueryResults) then
                    set AssociatorsOfQueryWmiClass = QueryResults
               else
                    set AssociatorsOfQueryWmiClass = nothing
               end if
          else     
               set AssociatorsOfQueryWmiClass = nothing
          end if


     End function

     '===================================================
     '  Function  : ReferencesOfQueryWmiClass
     '  Purpose   : Executes a REFERENCES OF WMI query and returns the object to the caller
     '  Arguments : hWMIService - WMI handle to execute the the query on
     '              sDevicePath - Path to the device to get the associators of
     '              sWhere      - Conditions on what is returned
     '                     
     '   Returns : Nothing
     '     Notes : The array that is passed in must be a dynamic size
     '===================================================
     Function ReferencesOfQueryWmiClass(byRef hWMIService, byVal sDevicePath, byVal sWhere)
          if IsObject(hWMIService) then
               dim WQL : WQL = "REFERENCES OF {" & sDevicePath & "}"
               if Len(sWhere) > 0 then
                    WQL = WQL & " WHERE " & sWhere
               end if
               dim QueryResults : Set QueryResults = hWMIService.ExecQuery(WQL)

               if not IsNothing(QueryResults) then
                    set ReferencesOfQueryWmiClass = QueryResults
               else
                    set ReferencesOfQueryWmiClass = nothing
               end if
          else     
               set ReferencesOfQueryWmiClass = nothing
          end if


     End function

     '===================================================
     '  Function  : IsIntelAdapter
     '  Purpose   : Checks if the adapter specified is an intel adapter
     '  Arguments : 
     '              oDevice - Device to check
     '
     '  Returns   :
     '    0  - adapter IS NOT Intel
     '    1  - adapter IS Intel 
     '    2  - not an adapter from IANet_PhysicalEthernetAdapter class
     '===================================================
     Private Function IsIntelAdapter(oDevice)

          on error resume next

          if UCASE(oDevice.CreationClassName) = "IANET_PHYSICALETHERNETADAPTER" then
               if err.number <> 0 then
                    IsIntelAdapter = NOT_AN_ADAPTER
                    exit function
               end if     
               
               if instr(UCASE(oDevice.PCIDeviceID), "VEN_8086") > 0 then
                   IsIntelAdapter = INTEL_ADAPTER
               else
                    IsIntelAdapter = THIRD_PARTY_ADAPTER
               end if
          else 
               IsIntelAdapter = NOT_AN_ADAPTER
          end if     
          
     end function

     '===================================================
     '  Function : SetAdapterSettings
     '   Purpose : Sets adapter settings
     ' Arguments : 
     '              hWMIServices  - a handle to a namespace which implements IANet_PhysicalEthernetAdapter
     '              sAdapter      - Instance (CDevice) of the adapter to be set on
     '              oSettingName  - Name of the setting to set
     '              sSettingValue - Value to set the setting to
     '===================================================
     Private Function SetAdapterSettings (hWMIServices, oAdapter, sSettingName, sSettingValue, sResult)
          dim IANet_Setting, i
          dim bValidSetting : bValidSetting = false
          dim bValidValue : bValidValue = false          
          dim bSetSuccess : bSetSuccess = false

          ' Make sure the inputs are not null or blank values
          ' Failing any one of these will immediately return a failure
          
          ' Check the WMI handle
          if IsNothing(hWMIServices) = true then
               sResult = "WMI Handle cannot be blank/NULL"
               SetAdapterSettings = false
               exit function
          end if

          ' Check the adapter object
          if IsNothing(oAdapter) = true then
               sResult = "Adapter cannot be NULL"
               SetAdapterSettings = false
               exit function
          end if
          
          ' Check the setting
          if IsNothing(sSettingName) = true then
               sResult = "Setting Name cannot be blank/NULL"
               SetAdapterSettings = false
               exit function
          end if
          
          ' Check the value
          if IsNothing(sSettingValue) = true then
               sResult = "Setting Value cannot be blank/NULL"
               SetAdapterSettings = false
               exit function
          end if

          ' We made it this far, the inputs were all provided

          ' Query the WMI for the settings that apply to this adapter
          dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")
          dim IANet_Settings : Set IANet_Settings = AssociatorsOfQueryWmiClass (hWMIServices, SValueSet, oAdapter.Path, "ResultClass = IANet_AdapterSetting")

          ' Loop through all the returned settings
          for each IANet_Setting in IANet_Settings
               ' Check if we already found the setting specified, no matter what, we can leave the loop
               if bValidSetting = true then
                    exit for
               end if

               ' Check if the current setting is the specified setting
               if UCASE(IANet_Setting.Caption) = UCASE(sSettingName) then
                    ' Set the bValidSetting variable so we stop looping through settings
                    bValidSetting = true
                    
                    on error resume next
                    err.clear
                    dim nPossibleValueCount : nPossibleValueCount = UBound(IANet_Setting.PossibleValues)
                    if err.number <> 0 then
                         if IsNumeric(sSettingValue) then
                              
                              if sSettingValue >= IANet_Setting.min AND sSettingValue <= IANet_Setting.max then
                                   bValidValue = true     
                              end if
                         else
                              bValidValue = false
                         end if
                    else
                         ' Settings match, now loop through the possible values
                              For i = 0 To UBound(IANet_Setting.PossibleValues)
                              ' Check if the specified setting is a possible value
                                   if UCASE(IANet_Setting.PossibleValues(i)) = UCASE(sSettingValue) then      
                                        bValidValue = true
                                        exit for
                                   end if
                              next
                    end if
                    
                    if bValidValue then
                         dim ClientID, dummyResult
                         bValidValue = true
                         ' Do a BeginApply to acquire a lock in Middleware to prepare to write a setting
                         If BeginApply(hWMIServices, ClientID, sResult) = False Then
                              ' We failed, set the success bool to false and update 
                              ' the sResult telling where we failed and stop looping
                              bSetSuccess = false
                              sResult = "Failed to BeginApply"
                              Err.Clear
                              exit for
                         End If

                         ' Add the ClientID so the lock allows us to apply the setting
                         SValueSet.Add "ClientSetId", ClientID

                         ' Update the setting to what we want it to be
                         IANet_Setting.CurrentValue = sSettingValue

                         ' Call WMI to update the setting
                         Set dummyResult = IANet_Setting.Put_(wbemFlagUseAmendedQualifiers, SValueSet)

                         ' Try to apply the setting
                         if Apply (hWMIServices, ClientID, sResult) = false  then 
                              ' We failed, set the success bool to false and update 
                              ' the sResult telling where we failed and stop looping
                              bSetSuccess = false
                              sResult = "Failed to apply setting"
                              Err.Clear
                              exit for
                         end if

                         ' If we've made it this far, the WMI calls did not fail.  
                         ' Set the success bool to true
                         bSetSuccess = true
                         exit for                              
                    end if
               end if
          next

          ' bValidSetting is false if no match is found, set the sResult value
          if bValidSetting = false then
               sResult = "SettingName not found: " & sSettingName
          elseif bValidValue = false then
               sResult = "SettingValue not valid: " & sSettingValue  
          end if
          
          ' Set the return value to be the result of setting the setting.  
          ' This will be false if the setting was not valid or if the WMI
          ' calls to update the setting fail.  Otherwise it is true.
          SetAdapterSettings = bSetSuccess
          
     end function     

     '===================================================
     '  Function : GetTeams
     '   Purpose : Gets all teams existing on the system
     ' Arguments : 
     '              hWMIServices  - a handle to a namespace which implements IANet_LogicalEthernetAdapter
     '              sResult       - result string that relays errors
     '===================================================
     Private Function EnumerateTeams(hWMIServices, byref sResult)
          
          if IsNothing(hWMIServices) then 
               set EnumerateTeams = nothing
               exit function
          end if

          dim querySet
          set querySet = SelectQueryWmiClass(hWMIServices, "*", "IANet_LogicalEthernetAdapter", "")
        
          dim retTeamList()
          if not IsNothing(querySet) then
               dim setting
               for each setting in querySet
                    pushobject retTeamList, setting
               next
          
               ' sort the team list
               ' Requesting Ubound() on empty arrays throws Err 
               ' so handle it here and clear it later
               On Error Resume Next
                    Dim i , j , temp
                    dim NumberOfTeams :  NumberOfTeams = Ubound(retTeamList) - 1

                    if err.number <> 0 then
                         EnumerateTeams = nothing                    
                         exit function
                    end if     
                    
                    For i = NumberOfTeams to 0 Step - 1 
                         For j = 0 to i
                              If retTeamList(j).DeviceID > retTeamList(j+1).DeviceID Then
                                   Set temp = retTeamList(j+1)
                                   Set retTeamList(j+1) = retTeamList(j)
                                   Set retTeamList(j) = temp
                              End If     
                         Next
                    Next
                    
                    Err.Clear
               on error goto 0     

               EnumerateTeams = retTeamList
          else
               EnumerateTeams = nothing
               sResult = "No results returned from WMI query"
          end if

     end function

     '===================================================
     '  Function : GetAdaptersInTeam
     '   Purpose : Get all adapters in the specified team
     ' Arguments : 
     '              hWMIServices  - a handle to the WMI
     '              oTeam         - Instance of the team to get member adapters for
     '===================================================
     private Function GetAdaptersInTeam(hWMIService, oTeam)
          if IsNothing(hWMIService) then 
               set GetAdaptersInTeam = nothing
               exit function
          end if

          ' if the team handle is bad, bail
          if IsNothing(oTeam) then 
               set GetAdaptersInTeam = nothing
               exit function
          end if

          ' Create the value set that will be passed with the WMI query
          dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")

          ' Get the same instance of the team but in the IANET_TeamOfAdapters class
          dim TeamOfAdaptersInstance : set TeamOfAdaptersInstance = AssociatorsOfQueryWmiClass(hWMIService, SValueSet, oTeam.Path_.Path, "ResultRole=SameElement")

          dim TeamInstance
          ' Get the team instance, this for loop will only go once as there is only one instance
          for each TeamInstance in TeamOfAdaptersInstance
               'Using the IANET_TeamOfAdapters instance, we can get the adapters that are part of this team
               dim TeamMembers : Set TeamMembers = AssociatorsOfQueryWmiClass (hWMIService, SValueSet, TeamInstance.Path_.Path, "ResultRole=PartComponent")
          next

          ' if nothing came back from the query, there are no member adapters          
          if IsNothing(TeamMembers) then
               set GetAdaptersInTeam = nothing
          else
               ' set the return value to be the list of adapters
               set GetAdaptersInTeam = TeamMembers
          end if

     end function

     '===================================================
     '  Function : GetTeamInfo
     '   Purpose : Retrieves team settings and current values 
     ' Arguments : 
     '              hWMIServices - a handle to the WMI namespace
     '              oTeam        - the instance of the team to query on
     '===================================================
     Private Function GetTeamInfo (hWMIServices, oTeam)
          dim retSettingList : set retSettingList = nothing

          ' if the WMI handle is bad, bail out
          if IsNothing(hWMIServices) then 
               set GetTeamInfo = nothing
               exit function
          end if

          ' if the team handle is bad, bail
          if IsNothing(oTeam) then 
               set GetTeamInfo = nothing
               exit function
          end if

          ' Get the Team from WMI
          dim TeamCollection
          set TeamCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_TeamOfAdapters", "Name='" & oTeam.DeviceId & "'")

          if not IsNothing(TeamCollection) then
               dim TeamInstance
               ' The TeamCollection item will be a collection with only one member
               ' which is the team instance we want.  Do another loop to get the first 
               ' item in the collection.  This will only loop once
               for each TeamInstance in TeamCollection
                    ' Set the return value to be the properties of the team object
                    set retSettingList = TeamInstance.Properties_
               next
          end if     

          ' set the return value for the function
          ' will be 'nothing' if the query failed
          set GetTeamInfo = retSettingList

     end function  

     '===================================================
     '  Function : RemoveTeam
     '   Purpose : Removes the specified team
     ' Arguments : 
     '              hWMIServices - a handle to the WMI namespace
     '              oTeam        - the instance of the team to query on
     '===================================================
     private function RemoveTeam(hWMIServices, oTeam)
          ' if the WMI handle is bad, bail out
          if IsNothing(hWMIServices) then 
               set RemoveTeam = nothing
               exit function
          end if

          ' if the team handle is bad, bail
          if IsNothing(oTeam) then 
               set RemoveTeam = nothing
               exit function
          end if

          ' Create the value set that will be passed with the WMI query
          dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")
          dim bRemoveSuccess : bRemoveSuccess = true
          dim ClientID, sReturn
          If BeginApply(hWMIServices, ClientID, sResult) = False Then
               ' We failed, set the success bool to false and update 
               ' the sResult telling where we failed and stop looping
               bRemoveSuccess = false
               sResult = "Failed to BeginApply"
               Err.Clear
               exit function
          End If

          on error resume next
          ' Add the ClientID so the lock allows us to apply the setting
          SValueSet.Add "ClientSetId", ClientID

          ' Remove the team
          oTeam.Delete_ 0, SValueSet

	  if Err <> 0 then
		bRemoveSuccess = false
	  end if

          on error goto 0
          
          ' Try to apply the setting
          if Apply (hWMIServices, ClientID, sResult) = false  then 
               ' We failed, set the success bool to false and update 
               ' the sResult telling where we failed and stop looping
               bRemoveSuccess = false
               sResult = "Failed to apply setting"
               Err.Clear
               exit function
          end if

          RemoveTeam = bRemoveSuccess
     end function

     '===================================================
     '  Function  : RemoveAdapterFromTeam
     '  Purpose   : Removes the specified team
     '  Arguments : 
     '              hWMIServices - a handle to the WMI namespace
     '              oAdapter     - the instance of the adpater to remove
     '              sResult      - Error string used to pass underlying error message to the user
     '  Return    :
     '              true  - if there were no errors
     '              false - if something failed.  
     '===================================================
     private function RemoveAdapterFromTeam(hWMIServices, oAdapter, sResult)
          if IsNothing(hWMIServices) then
               RemoveAdapterFromTeam = false
               exit function
          end if
          
          if IsNothing(oAdapter) then
               RemoveAdapterFromTeam = false
               exit function
          end if

          dim oMemberAdapterInstance, oMemberAdapterCollection
          set oMemberAdapterCollection = ReferencesOfQueryWmiClass(hWMIServices, oAdapter.DeviceInstance.Path_, "ResultClass = IANet_TeamedMemberAdapter")

          dim bFoundAdapter : bFoundAdapter = false
          dim bSuccess : bSuccess = true
          for each oMemberAdapterInstance in oMemberAdapterCollection
               ' Since we're in here, the adapter is associated with a team.
               bFoundAdapter = true

               dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")

               ' Get the instance in TeamOfAdapters so we can extract the team name
               dim oTeamCollection, oTeamInstance
               set oTeamCollection = AssociatorsOfQueryWmiClass(hWMIServices, SValueSet, oAdapter.DeviceInstance.Path_, "ResultClass = IANet_TeamOfAdapters")

               ' Loop through the team collection to get our single team instance                   
               for each oTeamInstance in oTeamCollection
                    sResult = oTeamInstance.Caption
                    exit for
               next
               
               dim ClientID, dummyResult
               ' Do a BeginApply to acquire a lock in Middleware to prepare to write a setting
               If BeginApply(hWMIServices, ClientID, sResult) = False Then
                    ' We failed, set the success bool to false and update 
                    ' the sResult telling where we failed and stop looping
                    sResult = "Failed to BeginApply"
                    bSuccess = false
                    Err.Clear
                    exit for
               End If

               ' The code between the BeginApply and Apply must ignore issues.
               ' The WMI will be left in a bad state if the scrip bails before 
               ' calling apply.
               on error resume next

               ' Add the ClientID so the lock allows us to apply the setting
               SValueSet.Add "ClientSetId", ClientID

               oMemberAdapterInstance.Delete_ 0, SValueSet

               ' Have the code stop on all errors after this point
               on error goto 0
               
               ' Try to apply the setting
               if Apply (hWMIServices, ClientID, sResult) = false  then 
                    ' We failed, set the success bool to false and update 
                    ' the sResult telling where we failed and stop looping
                    sResult = "Failed to apply setting"
                    bSuccess = false
                    Err.Clear
                    exit for
               end if
               exit for
          next 

          if bFoundAdapter = false then
               sResult = "Adapter not a member of a team."
               bSuccess = false
          end if
          
          RemoveAdapterFromTeam = bSuccess 
     end function

     

     '===================================================
     '  Function  : ModifyTeamInfo
     '  Purpose   : Retrieves team settings and current values 
     '  Arguments : 
     '              hWMIServices  - a handle to the WMI namespace
     '              oTeam         - the instance of the team to query on
     '              sSettingName  - name of the setting to change
     '              sSettingValue - value to change it to
     '              sResult       - Error string used to pass underlying error message to the user
     '  Return    :
     '              true  - if there were no errors
     '              false - if something failed.  
     '===================================================
     private function ModifyTeamInfo(hWMIServices, oTeam, sSettingName, sSettingValue, byref sResult)
          ' if the WMI handle is bad, bail out
          if IsNothing(hWMIServices) then 
               ModifyTeamInfo = false
               exit function
          end if

          ' if the team handle is bad, bail
          if IsNothing(oTeam) then 
               ModifyTeamInfo = false
               exit function
          end if

          if sSettingName = "" then 
               ModifyTeamInfo = false
               exit function
          end if

          if sSettingValue = "" then 
               ModifyTeamInfo = false
               exit function
          end if

          ' Clear the sResult string
          sResult = ""
          
          dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")
          
          ' Query the WMI for the settings that apply to this team
          dim TeamOfAdaptersCollection : Set TeamOfAdaptersCollection = AssociatorsOfQueryWmiClass (hWMIServices, SValueSet, oTeam.Path_, "ResultClass = IANet_TeamOfAdapters")
          dim TeamOfAdaptersInstance

          for each TeamOfAdaptersInstance in TeamOfAdaptersCollection
               dim ClientID, dummyResult
               ' Do a BeginApply to acquire a lock in Middleware to prepare to write a setting
               If BeginApply(hWMIServices, ClientID, sResult) = False Then
                    ' We failed, set the success bool to false and update 
                    ' the sResult telling where we failed and stop looping
                    sResult = "Failed to BeginApply"
                    Err.Clear
                    exit for
               End If

               ' The code between the BeginApply and Apply must ignore issues.
               ' The WMI will be left in a bad state if the scrip bails before 
               ' calling apply.
               on error resume next
               ' Add the ClientID so the lock allows us to apply the setting
               SValueSet.Add "ClientSetId", ClientID

                 ' Update the setting to what we want it to be
               TeamOfAdaptersInstance.Properties_.Item(sSettingName).value = sSettingValue
               
               ' Call WMI to update the setting
               TeamOfAdaptersInstance.put_ wbemFlagUseAmendedQualifiers, SValueSet

               if Err <> 0 then
                    sResult = "Failed to set setting: " & sSettingName
               end if
               
               ' Have the code stop on all errors after this point
               on error goto 0
               
               ' Try to apply the setting
               if Apply (hWMIServices, ClientID, sResult) = false  then 
                    ' We failed, set the success bool to false and update 
                    ' the sResult telling where we failed and stop looping
                    sResult = "Failed to apply setting"
                    Err.Clear
                    exit for
               end if
          next 

          ' if sResult is not a blank string, there was an error that populated it
          ' so we should return false, true otherwise
          if sResult <> "" then
               ModifyTeamInfo = false
          else
               ModifyTeamInfo = true
          end if     
          
     end function

     '===================================================
     '  Function  : GetTeamSetting
     '  Purpose   : Gets a specified Team setting
     '  Arguments : 
     '              hWMIServices  - a handle to a namespace which implements IANet_PhysicalEthernetTeam
     '              sTeam         - Instance of the Team to be set on
     '              oSettingName  - Name of the setting to set
     '              sResult       - return string to return errors to the calling function
     '  Return    :
     '              WMI object representing the Setting desired 
     '              This will return 'Nothing' if it is not found 
     '===================================================
     private function GetTeamSetting(hWMIServices, oTeam, sSettingName, byref sResult)
          ' if the WMI handle is bad, bail out
          if IsNothing(hWMIServices) then 
               set GetTeamSetting = false
               exit function
          end if

          ' if the team handle is bad, bail
          if IsNothing(oTeam) then 
               set GetTeamSetting = false
               exit function
          end if

          if sSettingName = "" then 
               set GetTeamSetting = false
               exit function
          end if

          dim whereStatement, querySet 
          dim retSetting : set retSetting = nothing
          
          ' Form the WHERE statment to check the adapter GUID and the setting name
          whereStatement = "ParentID='" & oTeam.DeviceID & "' AND Caption='" & sSettingName & "'"

          set querySet = SelectQueryWmiClass(hWMIServices, "*", "IANet_TeamSetting", whereStatement)

          ' if something was returned, it is in the form of a collection despite being only a single item
          if not IsNothing(querySet) then
               dim setting
               ' start a loop to get the first instance of the collection and set it to the return value
               ' This should only happen once.
               for each setting in querySet
                    set retSetting = setting
                    exit for
               next
          end if

          if IsNothing(retSetting) then
               ' Set the sResult variable so the calling function knows what went wrong and can tell the user
               sResult = "Setting not found: " & sSettingName
          end if

          set GetTeamSetting = retSetting
          
     end function

     '===================================================
     '  Function  : GetTeamSettings
     '  Purpose   : Retrieves Team settings and current values 
     '  Arguments : 
     '              hWMIServices - a handle to a namespace which implements IANet_LogicalEthernetAdapter
     '              oTeam        - the instance of the team to query on
     '  Return    :
     '              WMI collection object that holds all settings related to the team
     '              This will return 'nothing' if the query fails.       
     '===================================================
     Private Function GetTeamSettings (hWMIServices, oTeam)
          if IsNothing(hWMIServices) then 
               set GetTeamSettings = nothing
               exit function
          end if

          if IsNothing(oTeam) then 
               set GetTeamSettings = nothing
               exit function
          end if

           set GetTeamSettings = SelectQueryWmiClass(hWMIServices, "*", "IANet_TeamSetting", "ParentID='" & oTeam.DeviceId & "'")
     end function     

     '===================================================
     '  Function  : SetTeamSetting
     '  Purpose   : Sets Team settings
     '  Arguments : 
     '              hWMIServices  - a handle to a namespace which implements IANet_PhysicalEthernetTeam
     '              sTeam         - Instance of the Team to be set on
     '              sSettingName  - Name of the setting to set
     '              sSettingValue - Value to set the setting to
     '              sResult       - return string to return errors to the calling function
     '  Return    :
     '              true  - if there were no errors
     '              false - if something failed.  
     '===================================================
     Private Function SetTeamSetting (hWMIServices, oTeam, sSettingName, sSettingValue, sResult)
          dim bSetSuccess : bSetSuccess = false

          ' Make sure the inputs are not null or blank values
          ' Failing any one of these will immediately return a failure
          
          ' Check the WMI handle
          if IsNothing(hWMIServices) = true then
               sResult = "WMI Handle cannot be blank/NULL."
               SetTeamSetting = false
               exit function
          end if

          ' Check the Team object
          if IsNothing(oTeam) = true then
               sResult = "Team cannot be NULL."
               SetTeamSetting = false
               exit function
          end if
          
          ' Check the setting
          if IsNothing(sSettingName) = true then
               sResult = "SettingName cannot be blank/NULL."
               SetTeamSetting = false
               exit function
          end if
          
          ' Check the value
          if IsNothing(sSettingValue) then
               sResult = "SettingValue must specified."
               SetTeamSetting = false
               exit function
          end if

          if UCASE(sSettingName) = "USERSELECTEDADDRESS" then
               if not len(sSettingValue) = 12 then
                    sResult = "SettingValue is not the correct length.  Must be 12 HEX characters long."
                    SetTeamSetting = false
                    exit function
               end if

               if UCASE(sSettingValue) = "FFFFFFFFFFFF" then
                    sResult = "SettingValue cannot be the Broadcast address."
                    SetTeamSetting = false
                    exit function
               end if


               if not IsHexString(sSettingValue) then
                    sResult = "SettingValue is not a valid HEX value."
                    SetTeamSetting = false
                    exit function
               end if
          end if

          ' We made it this far, the inputs were all provided and potentially valid

          ' Query the WMI for the settings that apply to this Team
          dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")
          dim IANet_Settings : Set IANet_Settings = AssociatorsOfQueryWmiClass (hWMIServices, SValueSet, oTeam.Path_.Path, "ResultClass = IANet_TeamSetting")
          dim IANet_Setting : set IANet_Setting = nothing
          dim setting
          for each setting in IANet_Settings
               if UCASE(setting.caption) = UCASE(sSettingName) then
                    set IANet_Setting = setting
                    exit for
               end if     
          next

          if IsNothing(IANet_Setting) then
               sResult = "SettingName was not found."
               Err.Clear
               SetTeamSetting = false
               exit function
          end if
          
          on error resume next

          ' Get the min and max values for the setting
          dim min : min = IANet_Setting.min
          dim max : max = IANet_Setting.max
        
          dim bValidValue : bValidValue = false
          
          ' If there was no error getting those values, check to see if the 
          ' passed in value fits in the range
          if err.number = 0 then
              if CInt(min) <= CInt(sSettingValue) AND CInt(max) >= CInt(sSettingValue) then
                   bValidValue = true
              else
                   sResult = "SettingValue is not valid. Must be between " & IANet_Setting.min & " and " & IANet_Setting.max & "."
                   Err.Clear
                   bValidValue = false
              end if
          else
              dim i
              ' When we get an error, min and max values dont exist
              ' Check the PossibleValues array
              For i = 0 To UBound(IANet_Setting.PossibleValues)
                   ' Check if the specified setting is a possible value
                   if UCASE(CStr(IANet_Setting.PossibleValues(i)))= UCASE(sSettingValue) then      
                        bValidValue = true
                        exit for
                   end if
              next
              if bValidValue = false then
                   sResult = "SettingValue is not valid: " & sSettingValue
              end if
          end if

          if bValidValue then
               dim ClientID, dummyResult

               ' Do a BeginApply to acquire a lock in Middleware to prepare to write a setting
               If BeginApply(hWMIServices, ClientID, sResult) = False Then
                    ' We failed, set the success bool to false and update 
                    ' the sResult telling where we failed and stop looping
                    sResult = "Failed to BeginApply"
                    Err.Clear
                    SetTeamSetting = false
                    exit function
               End If

               on error resume next
               
                    ' Add the ClientID so the lock allows us to apply the setting
                    SValueSet.Add "ClientSetId", ClientID

                    ' Update the setting to what we want it to be
                    IANet_Setting.CurrentValue = sSettingValue

                    ' Call WMI to update the setting
                    Set dummyResult = IANet_Setting.Put_(wbemFlagUseAmendedQualifiers, SValueSet)
                    
               on error goto 0

               ' Try to apply the setting
               if Apply (hWMIServices, ClientID, sResult) = false  then 
                    ' We failed, set the success bool to false and update 
                    ' the sResult telling where we failed and stop looping
                    sResult = "Failed to apply setting"
                    Err.Clear
                    SetTeamSetting = false
                    exit function
               end if

               bSetSuccess = true
          end if     
           
          SetTeamSetting = bSetSuccess          
     end function  


     
     '===================================================
     '  Function : SetTeamMemberAdapterPriority
     '   Purpose : Sets the priority (Primary or Secondary) on an adapter in a team
     '   Input   : 
     '              hWMIServices - a handle to the WMI
     '              oAdapter     - Adapter to set
     '              sPriority    - "Primary" or "Secondary"
     '              sResult      - Error string used to pass underlying error message to the user
     '
     '   Returns :  true if there are no errors
     '              false otherwise, sResult will have an error string
     '===================================================
     private Function SetTeamMemberAdapterPriority(hWMIServices, oAdapter, sPriority, sResult)
          ' if the WMI handle is bad, bail out
          if IsNothing(hWMIServices) then 
               SetTeamMemberAdapterPriority = false
               exit function
          end if

          ' if the adapter object passed is not valid, exit
          if IsNothing(oAdapter) then 
               SetTeamMemberAdapterPriority = false
               exit function
          end if
          
          dim iPriority
          
          if sPriority = "" then
               SetTeamMemberAdapterPriority = false
               exit function
          else
               if UCASE(sPriority) = "NONE" then
                    iPriority = 0
               elseif UCASE(sPriority) = "PRIMARY" then
                    iPriority = 1
               elseif UCASE(sPriority) = "SECONDARY" then
                    iPriority = 2
               else
                    sResult = "Invalid Priority value"
                    SetTeamMemberAdapterPriority = false
                    exit function
               end if
          end if
          
          dim bSuccess : bSuccess = false
          dim adapter : set adapter = oAdapter.DeviceInstance
          
          ' Check if the adapter is in a team
          dim TeamedMemberAdapterCollection, TeamedMemberAdapterInstance
          set TeamedMemberAdapterCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_TeamedMemberAdapter", "PartComponent='" & adapter.Path_.RelPath & "'")
          
          ' If we enter this for loop, the adapter is part of a team
          dim bTeamedAdapter : bTeamedAdapter = false
          for each TeamedMemberAdapterInstance in TeamedMemberAdapterCollection
              bTeamedAdapter = true
              
              dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")
              dim ClientID, dummyResult
              ' Do a BeginApply to acquire a lock in Middleware to prepare to write a setting
              If BeginApply(hWMIServices, ClientID, sResult) = False Then
                   ' We failed, set the success bool to false and update 
                   ' the sResult telling where we failed and stop looping
                   sResult = "Failed to BeginApply"
                   Err.Clear
                   SetTeamSetting = false
                   exit function
              End If
       
              on error resume next
            
                   ' Add the ClientID so the lock allows us to apply the setting
                   SValueSet.Add "ClientSetId", ClientID

                   ' Update the setting to what we want it to be
                   TeamedMemberAdapterInstance.Properties_.Item("AdapterFunction").value = iPriority
                
                   ' Call WMI to update the setting
                   TeamedMemberAdapterInstance.Put_ wbemFlagUseAmendedQualifiers, SValueSet

              on error goto 0

              ' Try to apply the setting
              if Apply (hWMIServices, ClientID, sResult) = false  then 
                   ' We failed, set the success bool to false and update 
                   ' the sResult telling where we failed and stop looping
                   sResult = "Failed to apply setting"
                   Err.Clear
                   SetTeamSetting = false
                   exit function
              end if
               bSuccess = true
          next 
          
          ' If the adapter wasn't a part of a team, fail the function and set the sResult
          if bTeamedAdapter = false then
               sResult = "Adapter is not a member of a team."
               bSuccess = false
          end if
          
          
          SetTeamMemberAdapterPriority = bSuccess
     end function

    
     '===================================================
     '  Function : GetAdapterInfoInTeam
     '   Purpose : Get the info of an adapter in the specified team
     '   Input   : 
     '              hWMIServices - a handle to the WMI
     '              oAdapter     - Adapter to get Team info for
     '   Output  : 
     '              aSettings    - Array of strings with in the form of "<SettingName> - <SettingValue>"   
     '              sResult      - Error string used to pass underlying error message to the user
     '  Returns  :  true if there are no errors
     '              false otherwise, sResult will have an error string
     '===================================================
     private Function GetAdapterInfoInTeam(hWMIServices, oAdapter, byref aSettings, sResult)
          ' if the WMI handle is bad, bail out
          if IsNothing(hWMIServices) then 
               GetAdapterInfoInTeam = false
               exit function
          end if

          ' if the adapter object passed is not valid, exit
          if IsNothing(oAdapter) then 
               GetAdapterInfoInTeam = false
               exit function
          end if
          
          dim bSuccess : bSuccess = false
          dim adapter : set adapter = oAdapter.DeviceInstance
          
          ' Check if the adapter is in a team
          dim TeamedMemberAdapterCollection, TeamedMemberAdapterInstance
          set TeamedMemberAdapterCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_TeamedMemberAdapter", "PartComponent='" & adapter.Path_.RelPath & "'")
          
          ' If we enter this for loop, the adapter is part of a team
          dim bTeamedAdapter : bTeamedAdapter = false
          for each TeamedMemberAdapterInstance in TeamedMemberAdapterCollection
               bTeamedAdapter = true
               
               ' Get the IANet_TeamedMemberAdapter class definition so we can 
               ' use it to access the value map
               dim TeamedMemberAdapterClass : set TeamedMemberAdapterClass = hWMIServices.Get("IANet_TeamedMemberAdapter", wbemFlagUseAmEndedQualIfiers)
               
               ' Loop through the properties of the IANet_TeamedMemberAdapter instance
               dim prop, propValue
               for each prop in TeamedMemberAdapterInstance.Properties_
                    ' Filter out GroupComponent and PartComponent because the user has no need to see these paths
                    if UCASE(prop.name) <> "GROUPCOMPONENT" AND UCASE(prop.name) <> "PARTCOMPONENT" then
                        ' Convert the integer value to a string
                        propValue = GetPropertyValueFromValueMap(TeamedMemberAdapterClass, prop.name, prop.value)
                        
                        'if the returned value is blank, convert it to '<empty>'
                        if propValue <> "" then
                        else
                            propValue = "<empty>"
                        end if
                        
                        ' Push the setting name and value into the returned array
                        Push aSettings, prop.name & " - " & propValue
                        
                        ' Set success to true
                        bSuccess = true
                    end if
               next
               
               ' We only want this loop going once so exit after the first run.
               ' The collection thats being iterated will only be one instance
               exit for
          next
          
          ' If the adapter wasn't a part of a team, fail the function and set the sResult
          if bTeamedAdapter = false then
               sResult = "Adapter is not a member of a team."
               bSuccess = false
          end if
          
          GetAdapterInfoInTeam = bSuccess
     end function
     
     '===================================================
     '  Function : GetPropertyValueFromValueMap
     '   Purpose : Maps a setting integer value to a corresponding string value based on
     '             the ClassDefinitionObj
     ' Arguments : 
     '              ClassDefinitionObj - Definition of the class that the setting is a part of
     '              SettingName        - The setting to find in the 
     '              SettingValue       - value to convert
     '===================================================
     private function GetPropertyValueFromValueMap(ClassDefinitionObj, SettingName, SettingValue)
          on error resume next
          dim returnValue : returnValue = SettingValue
          
          dim valueMapArray : set valueMapArray = nothing
          dim valuesArray : set valuesArray = nothing
          
          if UCASE(ClassDefinitionObj.Path_.Class) = "IANET_TEAMEDMEMBERADAPTER" then
               '  wscript "Team"
               ' Get the Values array and loop through it
               set valueMapArray = ClassDefinitionObj.Properties_.Item(SettingName).Qualifiers_.Item("ValueMap")  
               set valuesArray = ClassDefinitionObj.Properties_.Item(SettingName).Qualifiers_.Item("Values")
               
          elseif Instr(UCASE(ClassDefinitionObj.Path_.Class), "IANET_ADAPTERSETTING") > 0 then
               '  wscript.echo "adapter"
               set valueMapArray = ClassDefinitionObj.Properties_.Item("PossibleValues")
               set valuesArray = ClassDefinitionObj.Properties_.Item("DescriptionMap")
          end if
          
          if IsNothing(valueMapArray) OR IsNothing(valuesArray) then
               GetPropertyValueFromValueMap = returnValue
               exit function
          end if
          
          ' Loop through the map to find the index of the SettingValue
          ' This will be the same index as in the Values array
          dim count
          dim valuesIndex : valuesIndex = -1
          for count = 0 to ubound(valueMapArray)
               ' Once we have the setting value index, save it off
               if ucase(valueMapArray(count)) = ucase(SettingValue) then
                    ValuesIndex = count
                    exit for
               end if
          next

           ' Make sure the index found above exists in the Values array 
           if ValuesIndex >= 0 AND ValuesIndex <= ubound(valuesArray) then
                ' Save off the string value to be returned to the caller 
                returnValue = valuesArray(ValuesIndex)
           end if
          
          GetPropertyValueFromValueMap = returnValue
     end function

     '===================================================
     '  Function : TestSwitchConfiguration
     '   Purpose : Tests the switch configuration on a given team to see 
     '             if it is configured correctly.
     ' Arguments : 
     '              hWMIServices - a handle to the WMI namespace
     '              oTeam        - instance of the team from IANet_LogicalEthernetAdapter
     '              sCommand     - Command to execute (Start, Cancel, Results)
     '              sResult      - Error string to tell what failed
     '===================================================
     private function TestSwitchConfiguration(hWMIServices, oTeam, sCommand, byref sResult)
          ' if the WMI handle is bad, bail out
          if IsNothing(hWMIServices) then
               sResult = "Invalid handle to the WMI."
               set TestSwitchConfiguration = nothing
               exit function
          end if

          ' if the team handle is bad, bail
          if IsNothing(oTeam) then 
               sResult = "Invalid team handle."
               set TestSwitchConfiguration = nothing
               exit function
          end if

          if sCommand = "" then
               sResult = "sCommand cannot be blank."
               set TestSwitchConfiguration = nothing
               exit function
          end if

          dim retObject : set retObject = nothing

          ' Get the Team from TeamOfAdapters
          dim TeamCollection
          set TeamCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_TeamOfAdapters", "Name='" & oTeam.DeviceId & "'")

          if not IsNothing(TeamCollection) then
               dim TeamInstance
               ' The TeamCollection item will be a collection with only one member
               ' which is the team instance we want.  Do another loop to get the first 
               ' item in the collection.  This will only loop once
               for each TeamInstance in TeamCollection
                    dim inParam
                    Set inParam = TeamInstance.Methods_.Item("TestSwitchConfiguration").InParameters

                    select case UCASE(sCommand)
                         case "START"
                              inParam.Cmd = CMD_START
                         case "CANCEL"     
                              inParam.Cmd = CMD_CANCEL
                         case "RESULTS"
                              inParam.Cmd = CMD_RESULTS
                         case else
                              sResult = "Invalid command: " & sCommand
                              set TestSwitchConfiguration = nothing               
                              exit function
                    end select

                    dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")

                    set retObject = TeamInstance.ExecMethod_("TestSwitchConfiguration", inParam, 0, SValueSet)
                    exit for 
               next
          end if     

          if IsNothing(retObject) then
               sResult = "Failed to execute TestSwitchFunction."
          end if
          
          set TestSwitchConfiguration = retObject
          
     end function

     '===================================================
     '  Function  : CreateVlanOnDevice
     '  Purpose   : Creates a VLAN on a specified device (Adapter or Team)
     '  Arguments : 
     '              hWMIServices - a handle to the WMI namespace
     '              oDevice      - Instance of the device to create the VLAN on
     '              sName        - Name for the VLAN
     '              sID          - ID for the VLAN (must be a number)
     '              sResult      - Error string to tell what failed
     '  Return    :
     '              true  - if there were no errors
     '              false - if something failed.  
     '===================================================
     private function CreateVlanOnDevice(hWMIServices, oDevice, sName, sID, byref sResult)
          if IsNothing(hWMIServices) then
               sResult = "Invalid WMI handle"
               CreateVlanOnDevice = false
               exit function
          end if

          if IsNothing(oDevice) then
               sResult = "Invalid instance of the device"
               CreateVlanOnDevice = false
               exit function
          end if

          ' Check for 3rd party adapters 
          if IsIntelAdapter(oDevice) = THIRD_PARTY_ADAPTER then
               sResult = "Adapter is a 3rd party device."
               CreateVlanOnDevice = false
               exit function
          end if

          if UCASE(sID) = "UNTAGGED" then
               sID = 0  
          end if
          
          if not IsNumeric(sID) then
               sResult = "VLAN ID must be numeric"
               CreateVlanOnDevice = false
               exit function
          end if  
          
          if CInt(sID) = 0 then
               sName = "Untagged VLAN"
          end if

          if sName = "" then
               sName = "VLAN" & sID
          end if 

          dim ClientID
          If BeginApply(hWMIServices, ClientID, sResult) = False Then
               ' We failed, set the success bool to false and update 
               ' the sResult telling where we failed and exit the function
               sResult = "Failed to BeginApply"
               Err.Clear
               CreateVlanOnDevice = false
               exit function
          End If

          ' This will be set true if there is an error when calling CreateVLAN in the WMI
          dim bIdAlreadyExists : bIdAlreadyExists = false
          
          on error resume next 
          
          dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")
          
          ' Add the ClientID so the lock allows us to apply the setting
          SValueSet.Add "ClientSetId", ClientID

          ' Get an instance of the device in the VLAN service class
          dim VlanObjectSet
          set VlanObjectSet = AssociatorsOfQueryWmiClass(hWMIServices, SValueSet, oDevice.Path_.Path, "ResultClass = IANet_802dot1QVLANService")

          ' Loop through the returned set, should only be one item in the collection
          dim VlanObject
	  dim bObjectFound
	  bObjectFound = false
          For Each VlanObject In VlanObjectSet
               ' Get a handle to the VLAN object in the VLAN service class
	       bObjectFound = true
               dim FinalVlanObject, InParameterObj, OutParameterObj
               Set FinalVlanObject = hWMIServices.Get(VlanObject.Path_.Path, ,SValueSet)                         

               ' Get the InParams for CreateVLAN
               ' and set them to the passed in values.
               Set InParameterObj = FinalVlanObject.Methods_.Item("CreateVLAN").InParameters.SpawnInstance_()
               InParameterObj.Name = sName                              
               InParameterObj.VLANNumber = sID

               ' Call the method to create the VLAN
               Set OutParameterObj = FinalVlanObject.ExecMethod_("CreateVLAN", InParameterObj, 0, SValueSet)
               if err.number <> 0 then
                    sResult = "VLAN ID may already exist."
                    bIdAlreadyExists = true
                    err.clear
               end if
               Exit For
          Next

          on error goto 0

	  if not bObjectFound then
		sResult = "Parent device does not support VLANs."
	  end if
          
          ' Try to apply the setting
          if Apply (hWMIServices, ClientID, sResult) = false  then 
               ' We failed, set the success bool to false and update 
               ' the sResult telling where we failed and exit the function
               sResult = "Failed to apply setting"
               Err.Clear
               CreateVlanOnDevice = false
               exit function
          end if

          ' if there was an error when calling CreateVLAN, it was likely because
          ' the VLAN id already exists.  The creation failed so we return FALSE
          if bIdAlreadyExists or not bObjectFound then 
               CreateVlanOnDevice = false
          else
               CreateVlanOnDevice = true
          end if
               
          
     end function
     
     '===================================================
     '  Function  : EnumerateVlansOnDevice
     '  Purpose   : Enumerates all VLANs on a specified device (Adapter or Team)
     '  Arguments : 
     '              hWMIServices - a handle to the WMI namespace
     '              oDevice      - Instance of the device to get all VLANs for
     '  Return    :
     '              Collection of VLANs associated with the passed in device
     '              Nothing if there is an error
     '===================================================
     private function EnumerateVlansOnDevice(hWMIServices, oDevice)
          if IsNothing(hWMIServices) then
               sResult = "Invalid WMI handle"
               set EnumerateVlansOnDevice = nothing
               exit function
          end if

          if IsNothing(oDevice) then
               sResult = "Invalid instance of the device"
               set EnumerateVlansOnDevice = nothing
               exit function
          end if

          dim VlansOnDevice : set VlansOnDevice = SelectQueryWmiClass(hWMIServices, "*", "IANet_VLAN", "ParentID='"& oDevice.DeviceID & "'")

          if VlansOnDevice.count = 0 then
               set VlansOnDevice = nothing
          end if

          set EnumerateVlansOnDevice = VlansOnDevice
         
     end function

     '===================================================
     '  Function  : RemoveVlanOnDevice
     '  Purpose   : Removes a specified VLAN from an Adapter or Team
     '  Arguments : 
     '              hWMIServices - a handle to the WMI namespace
     '              oDevice      - Device instance to remove the VLAN from
     '              VlanId       - ID number of the be removed
     '              sResult      - String to relay errors to the caller
     '  Return    :
     '              true  - if there were no errors
     '              false - if something failed, check sResult  
     '===================================================
     private function RemoveVlanOnDevice(hWMIServices, oDevice, VlanId, byref sResult)
          if IsNothing(hWMIServices) then 
               sResult = "Invalid handle to the WMI."
               RemoveVlanOnDevice = false
               exit function
          end if

          if IsNothing(oDevice) then 
               sResult = "Invalid device instance."
               RemoveVlanOnDevice = false
               exit function
          end if      

          if not IsNumeric(VlanId) then
               if UCASE(VlanID) = "UNTAGGED" then
                    VlanID = 0
               else
                    sResult = "Invalid VLAN ID."
                    RemoveVlanOnDevice = false
                    exit function
               end if     
          end if

          ' Create the WHERE case for the query
          dim sWhere
          sWhere = "ParentID='" & oDevice.DeviceID & "' AND VLANNumber='" & VlanId & "'" 

          ' Get the instance of the VLAN
          dim VlanCollection: set VlanCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_VLAN", sWhere)

          ' The returned collection is of one instance so we have to do this loop.
          ' It will only run once.  
          dim oVlan : set oVlan = nothing
          for each oVlan in VlanCollection
               ' Create the value set that will be passed with the WMI query
               dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")

               ' This will only be false if we fail to do the BeginApply or Apply
               dim bRemoveSuccess : bRemoveSuccess = true
               dim ClientID, sReturn
               If BeginApply(hWMIServices, ClientID, sResult) = False Then
                    ' We failed, set the success bool to false and update 
                    ' the sResult telling where we failed and stop looping
                    bRemoveSuccess = false
                    sResult = "Failed to BeginApply"
                    Err.Clear
                    exit for
               End If

               ' turn off error handling so we dont leave the system 
               ' in a bad state if theres an error in here
               on error resume next

               ' Add the ClientID so the lock allows us to apply the setting
               SValueSet.Add "ClientSetId", ClientID

               ' Remove the VLAN
               oVlan.Delete_ 0, SValueSet

               ' Turn back on error handling since we need to report errors 
               ' from here on out. 
               on error goto 0
               
               ' Try to apply the setting
               if Apply (hWMIServices, ClientID, sResult) = false  then 
                    ' We failed, set the success bool to false and update 
                    ' the sResult telling where we failed and stop looping
                    bRemoveSuccess = false
                    sResult = "Failed to apply setting"
                    Err.Clear
                    exit for
               end if
               exit for
          next

          if IsNothing(oVlan) then
               sResult = "VLAN ID does not exist on device."
               RemoveVlanOnDevice = false
               exit function
          end if
          
          ' Return whether or not there was an error along the way
          RemoveVlanOnDevice = bRemoveSuccess
          
     end function

     '===================================================
     '  Function  : GetVlanInfo
     '  Purpose   : Queries a specified VLAN for the settings
     '  Arguments : 
     '              hWMIServices - a handle to the WMI namespace
     '              oDevice      - Device instance to use
     '              VlanId       - ID number of the be removed
     '              sResult      - return string to return errors to the calling function
     '  Return    :
     '              VLAN properties object - if there were no errors
     '              Nothing - if something failed, check sResult  
     '===================================================
     private Function GetVlanInfo(hWMIServices, oDevice, VlanID, byref sResult)
          if IsNothing(hWMIServices) then 
               sResult = "Invalid handle to the WMI."
               set GetVlanInfo = nothing
               exit function
          end if

          if IsNothing(oDevice) then 
               sResult = "Invalid device instance."
               set GetVlanInfo = nothing
               exit function
          end if      

          ' if its not numeric, its not a valid VLAN ID
          if not IsNumeric(VlanID) then 
               if UCASE(VlanID) = "UNTAGGED" then
                    VlanID = 0
               else
                    sResult = "Invalid VLAN ID."
                    set GetVlanInfo = nothing
                    exit function
               end if     
          end if   
          
          ' Query for the instance
          dim VLANObj : set VLANObj = nothing
          dim sWhere : sWhere = "ParentID='" & oDevice.DeviceID & "' AND VLANNumber='" & VlanId & "'" 
          dim VlanCollection: set VlanCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_VLAN", sWhere)

          ' if we got something, set the return to be the properties_ object
          ' otherwise its still 'nothing'
          if not IsNothing(VlanCollection) then
               dim tempObj
               ' This collection will be one item in length.  We have to 
               ' enumerate through and set the return object
               for each tempObj in VlanCollection
                    set VLANObj = tempObj.properties_
                    exit for
               next
          end if

          set GetVlanInfo = VLANObj
          
     end function

     '===================================================
     '  Function  : ModifyVlanInfo
     '  Purpose   : Retrieves Vlan settings and current values 
     '  Arguments : 
     '              hWMIServices  - a handle to the WMI namespace
     '              oDevice       - Device instance to use     
     '              VlanID        - ID of the VLAN to use
     '              sSettingName  - name of the setting to change
     '              sSettingValue - value to change it to
     '              sResult       - Error string used to pass underlying error message to the user
     '  Return    :
     '              true  - if there were no errors
     '              false - if something failed. sResult will have a string describing the failure 
     '===================================================
     private function ModifyVlanInfo(hWMIServices, oDevice, VlanID, sSettingName, sSettingValue, byref sResult)
          ' if the WMI handle is bad, bail out
          if IsNothing(hWMIServices) then 
               sResult = "Invalid WMI handle."
               ModifyVlanInfo = false
               exit function
          end if

          if IsNothing(oDevice) then 
               sResult = "Invalid device instance."
               ModifyVlanInfo = false
               exit function
          end if      
          
          ' if the Vlan handle is bad, bail
          if not IsNumeric(VlanID) then 
               if UCASE(VlanID) = "UNTAGGED" then
                    VlanID = 0
               else
                    sResult = "VLAN ID not valid."
                    ModifyVlanInfo = false
                    exit function
               end if
          end if

          if sSettingName = "" then 
               sResult = "SettingName cannot be blank."
               ModifyVlanInfo = false
               exit function
          end if

          if sSettingValue = "" then 
               sResult = "SettingValue cannot be blank."
               ModifyVlanInfo = false
               exit function
          end if

          dim VlanInstance : set VlanInstance = nothing

          dim sWhere : sWhere = "ParentID='" & oDevice.DeviceID & "' AND VLANNumber='" & VlanId & "'" 
          dim VlanCollection: set VlanCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_VLAN", sWhere)

          ' We need to get the VLAN instance from the returned collection
          if not IsNothing(VlanCollection) then
               dim tempObj
               for each tempObj in VlanCollection
                    set VlanInstance = tempObj
                    exit for
               next
          end if

          ' If we didn't get the instance, the VLAN ID doesn't exist.
          ' Exit the function
          if IsNothing(VlanInstance) then
               sResult = "VLAN ID not found: " & VlanID
               ModifyVlanInfo = false
               exit function
          end if

          dim ClientID, dummyResult
          ' Do a BeginApply to acquire a lock in Middleware to prepare to write a setting
          If BeginApply(hWMIServices, ClientID, sResult) = False Then
               ' We failed, set the success bool to false and update 
               ' the sResult telling where we failed and stop looping
               sResult = "Failed to BeginApply"
               Err.Clear
               ModifyVlanInfo = false
               exit function
          End If

          ' The code between the BeginApply and Apply must ignore issues.
          ' The WMI will be left in a bad state if the scrip bails before 
          ' calling apply.
          on error resume next

          dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")
          
          ' Add the ClientID so the lock allows us to apply the setting
          SValueSet.Add "ClientSetId", ClientID

          ' Update the setting to what we want it to be
          VlanInstance.Properties_.Item(sSettingName).value = sSettingValue
          
          ' Call WMI to update the setting
          VlanInstance.put_ wbemFlagUseAmendedQualifiers, SValueSet

          ' Have the code stop on all errors after this point
          on error goto 0
          
          ' Try to apply the setting
          if Apply (hWMIServices, ClientID, sResult) = false  then 
               ' We failed, set the success bool to false and update 
               ' the sResult telling where we failed and stop looping
               sResult = "Failed to apply setting"
               Err.Clear
               ModifyVlanInfo = false
               exit function
          end if
          
          ' if sResult is not a blank string, there was an error that populated it
          ' so we should return false, true otherwise
          if sResult <> "" then
               ModifyVlanInfo = false
          else
               ModifyVlanInfo = true
          end if     

     end function
     
     '===================================================
     '  Function  : GetVlanSetting
     '  Purpose   : Queries a specified VLAN for the specified setting
     '  Arguments : 
     '              hWMIServices - a handle to the WMI namespace
     '              oDevice      - Device instance to use
     '              VlanId       - ID number of the be removed
     '              sSettingName - Name of the setting to retreive
     '              sResult      - return string to return errors to the calling function
     '  Return    :
     '              VLAN properties object - if there were no errors
     '              Nothing - if something failed, check sResult  
     '===================================================
     private Function GetVlanSetting(hWMIServices, oDevice, VlanID, sSettingName, byref sResult)
          if IsNothing(hWMIServices) then 
               sResult = "Invalid handle to the WMI."
               set GetVlanSetting = nothing
               exit function
          end if

          if IsNothing(oDevice) then 
               sResult = "Invalid device instance."
               set GetVlanSetting = nothing
               exit function
          end if      
          
          if not IsNumeric(VlanID) then 
               if UCASE(VlanID) = "UNTAGGED" then
                    VlanID = 0
               else
                    sResult = "Invalid VLAN ID."
                    set GetVlanSetting = nothing
                    exit function
               end if     
          end if   

          if sSettingName = "" then
               sResult = "Invalid SettingName."
               set GetVlanSetting = nothing
               exit function
          end if

          ' Query for the specified VLAN
          dim VlanSetting : set VlanSetting = nothing
          dim sWhere : sWhere = "ParentID='" & oDevice.DeviceID & "' AND VLANNumber='" & VlanId & "'" 
          dim VlanCollection: set VlanCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_VLAN", sWhere)
          dim bFoundVlan : bFoundVlan = false
          
          ' Make sure we got something before trying to get the setting
          if not IsNothing(VlanCollection) then
               dim tempObj
               
               ' This collection will be one item in length.  We have to 
               ' enumerate through and set the return object
               for each tempObj in VlanCollection
                    ' Now that we have the VLAN's GUID, we can now query the settings class.
                    dim VlanSettingsCollection
                    set VlanSettingsCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_VLANSetting", "ParentID='" & tempObj.Name & "'")

                    bFoundVlan = true
                    ' Try to get the setting
                    dim tempSettingObj
                    for each tempSettingObj in VlanSettingsCollection
                         if UCASE(tempSettingObj.caption) = UCASE(sSettingName) then
                              set VlanSetting = tempSettingObj
                         end if     
                    next
                    
                    if IsNothing(VlanSetting) then
                         sResult = "SettingName not found: " & sSettingName
                         set VlanSetting = nothing
                         err.clear
                    end if
                    exit for
               next
          end if

          if bFoundVlan = false then
               sResult = "VLAN ID not found: " & VlanID
               set VlanSetting = nothing
          end if
          set GetVlanSetting = VlanSetting
          
     end function

     '===================================================
     '  Function  : GetVlanSettings
     '  Purpose   : Retrieves VLAN settings and current values 
     '  Arguments : 
     '              hWMIServices - a handle to a namespace which implements IANet_LogicalEthernetAdapter
     '              oDevice      - Device instance to use     
     '              VlanID       - ID of the VLAN to query on
     '              sResult      - return string to return errors to the calling function
     '  Return    :
     '              WMI collection object that holds all settings related to the team
     '              This will return 'nothing' if the query fails.       
     '===================================================
     Private Function GetVlanSettings (hWMIServices, oDevice, VlanID, sResult)
          if IsNothing(hWMIServices) then 
               sResult = "Invalid WMI handle."
               set GetVlanSettings = nothing
               exit function
          end if

          if IsNothing(oDevice) then 
               sResult = "Invalid device instance."
               set GetVlanSettings = nothing
               exit function
          end if      

          if not IsNumeric(VlanID) then 
               if UCASE(VlanID) = "UNTAGGED" then
                    VlanID = 0
               else
                    sResult = "Invalid VLAN ID."
                    set GetVlanSettings = nothing
                    exit function
               end if     
          end if

          ' Query for the specified VLAN
          dim retVlanSettings : set retVlanSettings = nothing
          dim sWhere : sWhere = "ParentID='" & oDevice.DeviceID & "' AND VLANNumber='" & VlanId & "'" 
          dim VlanCollection: set VlanCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_VLAN", sWhere)

          dim bFoundVlan : bFoundVlan = false
          if not IsNothing(VlanCollection) then
               dim tempObj
               ' This collection will be one item in length.  We have to 
               ' enumerate through and set the return object
               for each tempObj in VlanCollection
                    bFoundVlan = true
                    ' Now that we have the VLAN's GUID, we can now query the settings class.
                    set retVlanSettings = SelectQueryWmiClass(hWMIServices, "*", "IANet_VLANSetting", "ParentID='" & tempObj.Name & "'")
                    exit for
               next
          end if
          
          if bFoundVlan = false then
               sResult = "VLAN ID not found"
               set retVlanSettings = nothing     
          end if     

          set GetVlanSettings = retVlanSettings
          
     end function 

     '===================================================
     '  Function  : SetVlanSetting
     '  Purpose   : Queries a specified VLAN for the specified setting
     '  Arguments : 
     '              hWMIServices  - a handle to the WMI namespace
     '              oDevice       - Device instance to use     
     '              VlanId        - ID number of the be removed
     '              sSettingName  - Name of the setting to retreive
     '              sSettingValue - Value to set the setting to
     '              sResult       - return string to return errors to the calling function
     '  Return    :
     '              True  - if there were no errors
     '              False - if something failed, check sResult  
     '                      sResult will have a value in it if false is returned
     '===================================================
     private Function SetVlanSetting(hWMIServices, oDevice, VlanID, sSettingName, sSettingValue, byref sResult)
          if IsNothing(hWMIServices) then 
               sResult = "Invalid handle to the WMI."
               SetVlanSetting = false
               exit function
          end if

          if IsNothing(oDevice) then 
               sResult = "Invalid device instance."
               SetVlanSetting = false
               exit function
          end if      

          if not IsNumeric(VlanID) then 
               if UCASE(VlanID) = "UNTAGGED" then
                    VlanID = 0
               else
                    sResult = "Invalid VLAN number."
                    SetVlanSetting = false
                    exit function
               end if     
          end if  

          if sSettingName = "" then
               sResult = "Invalid SettingName."
               SetVlanSetting = false
               exit function
          end if

          if sSettingValue = "" then
               sResult = "Invalid SettingName."
               SetVlanSetting = false
               exit function
          end if
          
          ' Query for the specified VLAN
          dim sWhere : sWhere = "ParentID='" & oDevice.DeviceID & "' AND VLANNumber='" & VlanId & "'" 
          dim VlanCollection: set VlanCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_VLAN", sWhere)

          dim bFoundVlan : bFoundVlan = false
          dim retValue : retValue = true
          dim VLANObj : set VLANObj = nothing
          
          if not IsNothing(VlanCollection) then
               ' This collection will be one item in length.  We have to 
               ' enumerate through and set the return object
               for each VlanObj in VlanCollection
                    bFoundVlan = true
                    dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")

                    ' Get the settings instance     
                    dim IANet_Settings : Set IANet_Settings = AssociatorsOfQueryWmiClass (hWMIServices, SValueSet, VlanObj.Path_.Path, "ResultClass = IANet_VLANSetting")
                    dim IANet_Setting : set IANet_Setting = nothing

                    ' Loop through until we find the setting we're looking for
                    dim setting
                    for each setting in IANet_Settings
                         if UCASE(setting.caption) = UCASE(sSettingName) then
                              set IANet_Setting = setting
                         end if     
                    next

                    
                    ' If IANet_Setting is still nothing, we didn't find the setting.
                    ' Exit the function
                    if IsNothing(IANet_Setting) then
                         sResult = "SettingName was not found."
                         Err.Clear
                         SetVlanSetting = false
                         exit function
                    end if
           
                    if IsNumeric(sSettingValue) then
                    
                        on error resume next
		                dim bValidValue : bValidValue = false
		    	        ' Get the min and max values for the setting
		    	        dim min : min = IANet_Setting.min
		    	        dim max : max = IANet_Setting.max

	            	    if err.number <> 0 then
	            	        min = 0
	            	        max = 1
	            	        Err.Clear
	            	    end if
		               
                    	' If there was no error getting those values, check to see if the 
                    	' passed in value fits in the range
                    
	                    if CInt(min) <= CInt(sSettingValue) AND CInt(max) >= CInt(sSettingValue) then
	                        bValidValue = true
	                    else
	                        sResult = "SettingValue is not valid. Must be between " & IANet_Setting.min & " and " & IANet_Setting.max & "."
	                        Err.Clear
	                        bValidValue = false
	                    end if
                    end if
		        if bValidValue then
		   
                    dim ClientID, dummyResult

                    ' Do a BeginApply to acquire a lock in Middleware to prepare to write a setting
                    If BeginApply(hWMIServices, ClientID, sResult) = False Then
                         ' We failed, set the success bool to false and update 
                         ' the sResult telling where we failed and stop looping
                         sResult = "Failed to BeginApply"
                         Err.Clear
                         SetVlanSetting = false
                         exit function
                    End If

                    ' Add the ClientID so the lock allows us to apply the setting
                    SValueSet.Add "ClientSetId", ClientID

                    ' Update the setting to what we want it to be
                    IANet_Setting.CurrentValue = sSettingValue

                    ' Call WMI to update the setting
                    Set dummyResult = IANet_Setting.Put_(wbemFlagUseAmendedQualifiers, SValueSet)

                    ' Try to apply the setting
                    if Apply (hWMIServices, ClientID, sResult) = false  then 
                         ' We failed, set the success bool to false and update 
                         ' the sResult telling where we failed and stop looping
                         sResult = "Failed to apply setting"
                         Err.Clear
                         SetVlanSetting = false
                         exit function
                    end if
                    retValue = true
                    exit for
              	end if
               next
               
          end if

          if bFoundVlan = false then
               sResult = "VLAN ID not found: " & VlanID
               retValue = false
          end if

          if bValidValue = false then
          	sResult = "Setting Value not a valid value : " & sSettingValue
          	retValue = false
          end if
          SetVlanSetting = retValue
          
     end function
     
     '===================================================
     '  Function : GetAdapterSetting
     '   Purpose : Gets specified adapter setting
     ' Arguments : 
     '              hWMIServices  - a handle to a namespace which implements IANet_PhysicalEthernetAdapter
     '              sAdapter      - Instance (CDevice) of the adapter to be get the setting on
     '              sSettingName  - Name of the setting to get
     '              sResult      - return string to return errors to the calling function
     '===================================================
     Private Function GetAdapterSetting (hWMIServices, oAdapter, sSettingName, byref sResult)
          dim retString : retString = ""
          dim querySet
          dim whereStatement

          if IsNothing(hWMIServices) then 
               set GetAdapterSetting = nothing
               exit function
          end if

          if IsNothing(oAdapter) then 
               set GetAdapterSetting = nothing
               exit function
          end if 

          if sSettingName = "" then 
               set GetAdapterSetting = nothing
               exit function
          end if

          dim retSetting : set retSetting = nothing
          
          ' Form the WHERE statment to check the adapter GUID and the setting name
          whereStatement = "ParentID='" & oAdapter.DeviceID & "' AND Caption='" & sSettingName & "'"
          
          set querySet = SelectQueryWmiClass(hWMIServices, "*", "IANet_AdapterSetting", whereStatement)
          ' if something was returned, it is in the form of a collection despite being only a single item
          if not IsNothing(querySet) then
               dim setting
               ' start a loop to get the first instance of the collection and set it to the return value
               ' This should only happen once.
               for each setting in querySet
                    set retSetting = setting
               next
          end if

          if IsNothing(retSetting) then
               ' Set the sResult variable so the calling function knows what went wrong and can tell the user
               retString = "Setting not found: " & sSettingName
          else 
               on error resume next
               ' try to get a friendly string for the setting value
               dim propValue
               propValue = GetPropertyValueFromValueMap(retSetting, retSetting.caption, retSetting.currentvalue)
               if err.number <> 0 then
                    propValue = Join(retSetting.CurrentValues, ",")
               end if
               
               if propValue = "" then
                    propValue = "<empty>"
               end if
               retString = retSetting.caption & " - " & propValue
          end if

          GetAdapterSetting = retString

     end function

     '===================================================
     '  Function : GetAdapterSettings
     '   Purpose : Retrieves adapter settings and current values 
     '   Input   : 
     '              hWMIServices - a handle to a namespace which implements IANet_PhysicalEthernetAdapter
     '              oAdapter     - adapter object to query on
     '   Output  : 
     '              returnArray  - Array of strings with in the form of "<SettingName> - <SettingValue>"   
     '   Return  :
     '              True  - if there were no errors
     '              False - If there were no settings found
     '===================================================
     Private Function GetAdapterSettings (hWMIServices, oAdapter, returnArray)
          if IsNothing(hWMIServices) then 
               GetAdapterSettings = false
               exit function
          end if
          dim bSuccess : bSuccess = false
          if IsNothing(oAdapter) then 
               GetAdapterSettings = false
               exit function
          end if
          dim AdapterSettingClass : set AdapterSettingClass = hWMIServices.Get("IANet_AdapterSetting", wbemFlagUseAmEndedQualIfiers)
          dim Settings : set Settings = SelectQueryWmiClass(hWMIServices, "*", "IANet_AdapterSetting", "ParentID='" & oAdapter.DeviceId & "'")
          
          if Settings.count <= 0 then
               GetAdapterSettings = false
               exit function
          end if
          
          on error resume next
          
          dim prop, propValue
          for each prop in Settings
               ' Convert the integer value to a string if we can
               propValue = GetPropertyValueFromValueMap(prop, prop.caption, prop.currentvalue)
               if err.number <> 0 then
                    ' if we had an error, chances are there is no prop.CurrentValue and the setting is an array
                    ' so we need to look at prop.CurrentValues and just return that as a string
                    propValue = join(prop.CurrentValues, ", ")
               end if  
               
               'if the returned value is blank, convert it to '<empty>'
               if propValue = "" then
                    propValue = "<empty>"
               end if
                
               ' Push the setting name and value into the returned array
               push returnArray, prop.caption & " - " & propValue
          next
          
          GetAdapterSettings = true
          
     end function     

     '===================================================
     '  Function : GetNDISVersionOnAdapter
     '   Purpose : Retrieves NDIS version on a given adapter
     ' Arguments : 
     '              hWMIServices - a handle to a namespace which implements IANet_PhysicalEthernetAdapter
     '              sGUID        - the GUID of the adapter to query on
     '              sResult      - return string to return errors to the calling function
     '===================================================
     private Function GetNDISVersionOnAdapter(hWMIServices, oAdapter, byref sResult)
          if IsNothing(hWMIServices) then 
               set GetNDISVersionOnAdapter = nothing
               exit function
          end if

          if IsNothing(oAdapter) then 
               set GetNDISVersionOnAdapter = nothing
               exit function
          end if

          set GetNDISVersionOnAdapter = ExecuteMethodOnAdapter(WbemServices, oAdapter, "GetNDISVersion", nothing, false, sResult)

     end function

     '===================================================
     '  Function : GetPowerUsageOptionsOnAdapter
     '   Purpose : Retrieves power usage options on a given adapter
     ' Arguments : 
     '              hWMIServices - a handle to a namespace which implements IANet_PhysicalEthernetAdapter
     '              oAdapter     - instance of the adapter  to query on
     '              sResult      - return string to return errors to the calling function
     '===================================================
     private Function GetPowerUsageOptionsOnAdapter(hWMIServices, oAdapter, byref sResult)
          if IsNothing(hWMIServices) then 
               set GetPowerUsageOptionsOnAdapter = nothing
               exit function
          end if

          if IsNothing(oAdapter) then 
               set GetPowerUsageOptionsOnAdapter = nothing
               exit function
          end if

          set GetPowerUsageOptionsOnAdapter = ExecuteMethodOnAdapter(WbemServices, oAdapter, "GetPowerUsageOptions", nothing, false, sResult)

     end function

     '===================================================
     '  Function :  IsPowerUsageOptionSupported
     '   Purpose :  Checks if the adapter supports a specified power usage option
     ' Arguments : 
     '              hWMIServices  - a handle to a namespace which implements IANet_PhysicalEthernetAdapter
     '              oAdapter      - Instance (CDevice) of the adapter to be set on
     '              sSettingName  - Name of the setting to set
     '              sResult       - return string to return errors to the calling function
     '===================================================
     private Function IsPowerUsageOptionSupported(hWMIServices, oAdapter, sSettingName, sResult)
          dim retValue
          dim powerUsageOptions
          set powerUsageOptions = GetPowerUsageOptionsOnAdapter(hWMIServices, oAdapter, sResult)'

          dim OptionValue : OptionValue = ""

          select case UCASE(sSettingName)
               case "ACBSMODE"
               case "AUTOPOWERSAVEMODEENABLED"
               case "ENHANCEDASPMPOWERSAVER"
               case "LINKSPEEDBATTERYSAVER"
               case "REDUCESPEEDONPOWERDOWN"
               case "SAVEPOWERNOWENABLED"
               case "SMARTPOWERDOWN"
               case "SYSTEMIDLEPOWERSAVER"
               case else
                    sResult = "Invalid power setting '" & sSettingName & "'"
                    IsPowerUsageOptionSupported = false
                    exit function     
          end select
          
          'on error resume next
          OptionValue = powerUsageOptions.Properties_.Item(sSettingName).value
          'on error goto 0
          
          if OptionValue <> "" then
               retValue = true
          else
               retValue = false
          end if     
     
          IsPowerUsageOptionSupported = retValue
     end function

     '===================================================
     '  Function : SetPowerUsageOptionsOnAdapter
     '   Purpose : Sets adapter power usage options
     ' Arguments : 
     '              hWMIServices  - a handle to a namespace which implements IANet_PhysicalEthernetAdapter
     '              oAdapter      - Instance (CDevice) of the adapter to be set on
     '              sSettingName  - Name of the setting to set
     '              sSettingValue - Value to set the setting to
     '              sResult       - return string to return errors to the calling function
     '===================================================
     private Function SetPowerUsageOptionsOnAdapter (hWMIServices, oAdapter, sSettingName, sSettingValue, byref sResult) 
          dim IANet_Setting, i
          dim bValidSetting : bValidSetting = false
          dim bValidValue : bValidValue = false          
          dim bSetSuccess : bSetSuccess = false

          ' Make sure the inputs are not null or blank values
          ' Failing any one of these will immediately return a failure

          ' Check the WMI handle
          if IsNothing(hWMIServices) = true then
               sResult = "Invalid WMI Handle"
               set SetPowerUsageOptionsOnAdapter = nothing
               exit function
          end if

          ' Check the adapter object
          if IsNothing(oAdapter) = true then
               sResult = "Invalid adapter Handle"
               set SetPowerUsageOptionsOnAdapter = nothing
               exit function
          end if

          ' Check the setting
          if IsNothing(sSettingName) = true then
               sResult = "Invalid SettingName"
               set SetPowerUsageOptionsOnAdapter = nothing
               exit function
          end if

          ' Check the value
          if IsNothing(sSettingValue) = true OR not IsNumeric(sSettingValue) then
               sResult = "Invalid SettingValue"
               set SetPowerUsageOptionsOnAdapter = nothing
               exit function
          end if

          if (sSettingValue <> 0) AND (sSettingValue <> 1) then
               sResult = "SettingValue must be 0 or 1"
               set SetPowerUsageOptionsOnAdapter = nothing
               exit function
          end if

          ' We made it this far, the inputs were all provided

          sResult = ""
          ' Now check that the setting is supported by the adapter
          if IsPowerUsageOptionSupported(hWMIServices, oAdapter, sSettingName, sResult) = false then
               if sResult = "" then
                    sResult = "Adapter does not support power setting '" & sSettingName & "'" 
               end if
               set SetPowerUsageOptionsOnAdapter = nothing
               exit function
          end if

          dim inParam
          Set inParam = oAdapter.DeviceInstance.Methods_.Item("SetPowerUsageOptions").InParameters
          select case UCASE(sSettingName)
               case "ACBSMODE"
                    inParam.ACBSMode = sSettingValue
               case "AUTOPOWERSAVEMODEENABLED"
                    inParam.AutoPowerSaveModeEnabled = sSettingValue
               case "ENHANCEDASPMPOWERSAVER"
                    inParam.EnhancedASPMPowerSaver = sSettingValue
               case "LINKSPEEDBATTERYSAVER"
                    inParam.LinkSpeedBatterySaver = sSettingValue
               case "REDUCESPEEDONPOWERDOWN"
                    inParam.ReduceSpeedOnPowerDown = sSettingValue
               case "SAVEPOWERNOWENABLED"
                    inParam.SavePowerNowEnabled = sSettingValue
               case "SMARTPOWERDOWN"
                    inParam.SmartPowerDown = sSettingValue
               case "SYSTEMIDLEPOWERSAVER"
                    inParam.SystemIdlePowerSaver = sSettingValue
               case else
                    sResult = "SettingName not valid: " & sSettingValue
                    SetPowerUsageOptionsOnAdapter = nothing
                    exit function     
          end select

          dim retObject : set retObject = nothing
          set retObject = ExecuteMethodOnAdapter(hWMIServices, oAdapter, "SetPowerUsageOptions", inParam, true, sResult)
          set SetPowerUsageOptionsOnAdapter = retObject
          

     end function
     
     '===================================================
     '  Function : GetAdapterPropertiesFromClass
     '   Purpose : Retrieves adapter properties and current values 
     ' Arguments : 
     '              hWMIServices - a handle to a WMI namespace 
     '              sClass       - the class to enumerate properties on
     '              oAdapter        - the GUID of the adapter to query on
     '===================================================
     Private Function GetPropertiesFromClass (hWMIServices, oAdapter, sClassType)
          dim sClass : sClass = ""

          if IsNothing(hWMIServices) then 
               set GetPropertiesFromClass = nothing
               exit function
          end if

          if IsNothing(oAdapter) then 
               set GetPropertiesFromClass = nothing
               exit function
          end if
          
          if LCase(sClassType) = "adapter" then
               sClass = "IANet_PhysicalEthernetAdapter"
          end if

          if sClass <> "" then
               set GetPropertiesFromClass = SelectQueryWmiClass(hWMIServices, "*", sClass, "DeviceID='" & oAdapter.DeviceID & "'")
          else
               set GetPropertiesFromClass = nothing
          end if
     end function    

     '===================================================
     '  Function  : ValidateTeamSettings
     '  Purpose   : Retrieves any warnings that would be given when creating
     '             a team of adapters with the given array.
     '  Arguments : 
     '              hWMIServices - a handle to a WMI namespace 
     '              AdapterArray - array of adapters objects to check
     '===================================================
     public function ValidateTeamSettings(hWMIServices, AdapterArray)
          dim inParam
          dim curAdapter
          dim adapterPathArray()
          dim oAdapter

          ' Check the WMI handle
          if IsNothing(hWMIServices) then 
               set ValidateTeamSettings = nothing
               exit function
          end if

          ' Check that the array has at least one item
          if ubound(AdapterArray) < 0 then
               set ValidateTeamSettings = nothing
               exit function
          end if

          ' for each adapter, fill an array with the path to be passed to the WMI function
          for each curAdapter in AdapterArray
                push adapterPathArray, curAdapter.Path
          next

          ' Get the first adapter in the list to execute the function on
          set oAdapter = AdapterArray(0)
          ' Get the in parameters for the function
          Set inParam = oAdapter.DeviceInstance.Methods_.Item("ValidateSettingOnNewTeam").InParameters
          ' Set the adapter list to the adapter path array generated above
          inParam.Adapters = adapterPathArray
          ' put a dummy setting name in since it is not used
          inParam.SettingName = "ValidateAll"

          ' Create a variable to hold any error strings
          dim sResult
          ' create a return object and set it to nothing
          dim retObject : set retObject = nothing
          ' execute the method
          set retObject = ExecuteMethodOnAdapter(hWMIServices, oAdapter, "ValidateSettingOnNewTeam", inParam, false, sResult)
          ' return the result
          set ValidateTeamSettings = retObject
          
     end function

     '===================================================
     '  Function  : ValidateSettingOnTeam
     '  Purpose   : Validates the synchornization of a setting to be changed on a team.
     '  Arguments : 
     '              hWMIServices  - a handle to a namespace which implements IANet_PhysicalEthernetAdapter
     '              oAdapter      - Instance (CDevice) of the adapter to be set on
     '              sSettingName  - Name of the setting to set
     '              sSettingValue - Value to set the setting to
     '              sResult       - return string to return errors to the calling function
     '  Return    :
     '              True  - if there were no errors
     '              False - if something failed, check sResult  
     '                      sResult will have a value in it if false is returned
     '===================================================
     Private Function ValidateSettingOnTeam (hWMIServices, oAdapter, sSettingName, sSettingValue, sResult)
          dim bSuccess : bSuccess = false

          ' Check that the WMI handle isn't null
          if IsNothing(hWMIServices) then
               ValidateSettingOnTeam = false
               exit function
          end if

          ' Check that the adapter handle isn't null
          if IsNothing(oAdapter) then
               ValidateSettingOnTeam = false
               exit function
          end if

          ' Check that the setting name isn't null
          if sSettingName = "" then
               ValidateSettingOnTeam = false
               exit function
          end if

          ' Check that the setting value isn't null
          if sSettingValue = "" then
               ValidateSettingOnTeam = false
               exit function
          end if

          dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")

          ' Get the Instance of the team that this adapter is a member of
          dim TeamOfAdaptersCollection, TeamOfAdaptersInstance
          set TeamOfAdaptersCollection = AssociatorsOfQueryWmiClass(hWMIServices, SValueSet, oAdapter.DeviceInstance.Path_, "ResultClass = IANet_TeamOfAdapters")

          dim bAdapterInTeam : bAdapterInTeam = false
          for each TeamOfAdaptersInstance in TeamOfAdaptersCollection
               ' The adapter is part of a team
               bAdapterInTeam = true

               ' Clear any errors
               err.Clear

               ' Make sure we continue since the inParams setting could fail.  
               on error resume next

               ' Get the input parameters object for the ValidateSetting function and 
               ' set them to the user given values
               dim inParams : set inParams = TeamOfAdaptersInstance.Methods_.Item("ValidateSetting").InParameters
               inParams.Adapter = oAdapter.Path
               inParams.SettingName = sSettingName

               ' Check if we failed to set the setting.
               ' Set the error to invalid setting and fail the function
               if err.number <> 0 then
                    sResult = "Invalid Setting Name"
                    ValidateSettingOnTeam = false
                    exit function
               end if

               ' Clear any errors
               err.Clear
               inParams.Value = sSettingValue
               
               ' Check if we failed to set the value.
               ' Set the error to invalid value and fail the function
               if err.number <> 0 then
                    sResult = "Invalid Setting Value"
                    ValidateSettingOnTeam = false
                    exit function
               end if

               ' Call the method and save the return value to be checked for success
               dim outParams : set outParams = nothing
               set outParams = TeamOfAdaptersInstance.ExecMethod_("ValidateSetting", inParams, 0, SValueSet)

               ' Make sure something was returned to check
               if not IsNothing(outParams) then
                    ' Check if no error was returned
                    if OutParams.ValResult = 0 then
                         bSuccess = true
                    else
                         ' Return the error code 
                         sResult = "Changing this setting will reload the team."
                         bSuccess = false
                    end if     
               else
                    ' if outParams is null, the function failed to execute
                    sResult = "Failed to execute method."
                    bSuccess = false
               end if     

               ' we only want this to run once so break here
               exit for
          next

          ' if the adapter wasn't found to be in a team, 
          ' that needs to be returned to the caller
          if bAdapterInTeam = false then
               sResult = "Adapter is not a member of a team."
               bSuccess = false
          end if

          ValidateSettingOnTeam = bSuccess
     end function  

     '===================================================
     '  Function  : ValidateAddAdapterToTeam
     '  Purpose   : Validates that the specified adapter can be added to the given team
     '  Arguments : 
     '              hWMIServices  - a handle to a namespace which implements IANet_PhysicalEthernetAdapter
     '              oAdapter      - Instance (CDevice) of the adapter to be set on
     '              oTeam         - Instance of the team to check
     '              sResult       - return string to return errors to the calling function
     '  Return    :
     '              True  - if there were no errors
     '              False - if something failed, check sResult  
     '                      sResult will have a value in it if false is returned
     '===================================================
     Private Function ValidateAddAdapterToTeam (hWMIServices, oAdapter, oTeam, sResult)
          dim bSuccess : bSuccess = false

          if IsNothing(hWMIServices) then
               sResult = "Invalid WMI handle"
               ValidateAddAdapterToTeam = false
               exit function
          end if

          if IsNothing(oAdapter) then
               sResult = "Invalid adapter instance"
               ValidateAddAdapterToTeam = false
               exit function
          end if

          if IsNothing(oTeam) then
               sResult = "Invalid team instance"
               ValidateAddAdapterToTeam = false
               exit function
          end if          

          ' Get the WMI instance of the adapter
          dim adapter : set adapter = oAdapter.DeviceInstance
          
          ' Check if the adapter is already in a team
          dim TeamedMemberAdapterCollection, TeamedMemberAdapterInstance
          set TeamedMemberAdapterCollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_TeamedMemberAdapter", "PartComponent='" & adapter.Path_.RelPath & "'")
          for each TeamedMemberAdapterInstance in TeamedMemberAdapterCollection
               sResult = "Adapter already a member of another team."
               ValidateAddAdapterToTeam = false
               exit function
          next
          
         dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")

          ' Get the team instance from IANet_TeamOfAdapters
          dim TeamOfAdaptersCollection, TeamOfAdaptersInstance
          set TeamOfAdaptersCollection = AssociatorsOfQueryWmiClass(hWMIServices, SValueSet, oTeam.Path_.Path, "ResultClass = IANet_TeamOfAdapters")

          dim AdapterArray
          Push AdapterArray, adapter.Path_

          ' Loop through the only item in the collection
          for each TeamOfAdaptersInstance in TeamOfAdaptersCollection
               dim inParams, outParams
               ' Get the input parameters and set it to the passed in adapter path
               set inParams = TeamOfAdaptersInstance.Methods_.Item("ValidateAddAdapters").InParameters.SpawnInstance_()

               inParams.Adapters = AdapterArray
               ' Execute the method
               set outParams = TeamOfAdaptersInstance.ExecMethod_("ValidateAddAdapters", inParams, 0, SValueSet)

               ' If the return value is 0, there were no errors.
               ' Otherwise the adapter cant be teamed.
               if outParams.ValResult = 0 then
                    bSuccess = true
               else
                    bSuccess = false
                    sResult = "Adapter cannot be added to " & oTeam.Caption
               end if
               exit for
          next

          ValidateAddAdapterToTeam = bSuccess

     end function

     '===================================================
     '  Function  : AddAdapterToTeam
     '  Purpose   : Adds the adapter the specified team
     '  Arguments : 
     '              hWMIServices - a handle to the WMI namespace
     '              oAdapter     - the instance of the adapter to add
     '              oTeam        - the instance of the team to use
     '              sResult      - Error string used to pass underlying error message to the user
     '  Return    :
     '              true  - if there were no errors
     '              false - if something failed.  
     '===================================================
     private function AddAdapterToTeam(hWMIServices, oAdapter, oTeam, sResult)
          dim bSuccess : bSuccess = true
          if IsNothing(hWMIServices) then
               AddAdapterToTeam = false
               exit function
          end if
          
          if IsNothing(oAdapter) then
               AddAdapterToTeam = false
               exit function
          end if

          if IsNothing(oTeam) then
               AddAdapterToTeam = false
               exit function
          end if

          ' Get the WMI instance from the CDevice
          dim adapter : set adapter = oAdapter.DeviceInstance
          
          dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")

          ' Get the class definition of IANet_TeamedMemberAdapter and spawn a new instance
          dim objInstance : set objInstance = hWMIServices.Get("IANet_TeamedMemberAdapter").SpawnInstance_

          ' Make sure we got something back
          if IsNothing(objInstance) then
               AddAdapterToTeam = false
               exit function
          end if

          ' Now get the instance of the team in IANet_TeamOfAdapters
          dim TeamOfAdapters, TeamOfAdaptersInstance : set TeamOfAdaptersInstance = nothing
          dim tempTeamInstance
          set TeamOfAdapters = AssociatorsOfQueryWmiClass(hWMIServices, SValueSet, oTeam.Path_.Path, "ResultClass=IANet_TeamOfAdapters")
          for each tempTeamInstance in TeamOfAdapters
               ' Save off the TOA instance to be used later
               set TeamOfAdaptersInstance = tempTeamInstance
               exit for
          next

          ' The team given is not a valid team
          if IsNothing(TeamOfAdaptersInstance) then
               sResult = "The given team is not valid."
               AddAdapterToTeam = false
               exit function 
          end if

          ' Set the GroupComponent to the path of the TOA instance
          objInstance.GroupComponent = TeamOfAdaptersInstance.Path_.RelPath

          ' Clear the error bits incase this fails
          err.clear
          
          ' Set the PartComponent to the path of the adapter
          objInstance.PartComponent = adapter.Path_.RelPath
          
          ' Check if there were any errors, there shouldn't be on this call.  
          if err.number <> 0 then
               sResult = "The given adapter is not valid."
               AddAdapterToTeam = false
               exit function 
          end if

          ' Check if the given adapter is already in a team
          dim TMACollection : set TMACollection = SelectQueryWmiClass(hWMIServices, "*", "IANet_TeamedMemberAdapter", "PartComponent='" & adapter.Path_.RelPath & "'" )

          dim tempObj
          for each tempObj in TMACollection
               ' if we came in here, the adapter is already part of a team.  
               sResult = "Adapter is already a member of a team"
               AddAdapterToTeam = false
               exit function 
          next

          dim ClientID, dummyResult
          ' Do a BeginApply to acquire a lock in Middleware to prepare to write a setting
          If BeginApply(hWMIServices, ClientID, sResult) = False Then
               ' We failed, set the success bool to false and update 
               ' the sResult telling where we failed and stop looping
               sResult = "Failed to BeginApply"
               bSuccess = false
               Err.Clear
               exit function
          End If

          ' The code between the BeginApply and Apply must ignore issues.
          ' The WMI will be left in a bad state if the scrip bails before 
          ' calling apply.
          on error resume next

          ' Add the ClientID so the lock allows us to apply the setting
          SValueSet.Add "ClientSetId", ClientID
          
          ' Clear the error bits incase this fails
          err.clear
          objInstance.Put_ wbemChangeFlagCreateOnly, SValueSet

          ' Check if there were any errors, there shouldn't be on this call.  
          if err.number <> 0 then
               sResult = "Failed to add adapter to the team"
               bSuccess = false
           end if

          ' Have the code stop on all errors after this point
          on error goto 0
          
          ' Try to apply the setting
          if Apply (hWMIServices, ClientID, sResult) = false  then 
               ' We failed, set the success bool to false and update 
               ' the sResult telling where we failed and stop looping
               sResult = "Failed to apply setting"
               bSuccess = false
               Err.Clear

          end if
          
          AddAdapterToTeam = bSuccess
     end function  
     
     '===================================================
     '  Function : ExecuteMethodOnAdapter
     '   Purpose : Executes a specified method on a given adapter 
     ' Arguments : 
     '              hWMIServices - a handle to a WMI namespace 
     '              oAdapter     - instance of the adapter to execute on
     '              sMethodName  - the class to enumerate properties on
     '              InParams     - parameters to be passed to the method
     '                             Pass 'nothing' if none exist
     '              bDoApply     - boolean value used to determine if the adapter needs to be restarted as a result of this call
     '              sResult      - return string to return errors to the calling function
     '===================================================
     Public Function ExecuteMethodOnAdapter(hWMIServices, oAdapter, sMethodName, InParams, bDoApply,  byRef sResult)
          if IsNothing(hWMIServices) then 
               set ExecuteMethodOnAdapter = nothing
               exit function
          end if

          if IsNothing(oAdapter) then 
               set ExecuteMethodOnAdapter = nothing
               exit function
          end if

          if sMethodName = "" then 
               set ExecuteMethodOnAdapter = nothing
               exit function
          end if
          
          dim retObject : set retObject = nothing
          dim adapter : set adapter = oAdapter.DeviceInstance
          
          dim bFoundMatch : bFoundMatch = false
          if IsNothing(InParams) then
               on error resume next
                    set retObject = adapter.ExecMethod_(sMethodName)                              
               on error goto 0
          else
               dim SValueSet : Set SValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")
               dim ClientID

               if bDoApply then
                    ' Do a BeginApply to acquire a lock in Middleware to prepare to write a setting
                    If BeginApply(hWMIServices, ClientID, sResult) = false Then
                    
                         ' We failed, update the sResult telling where 
                         ' we failed and stop looping
                         sResult = "Failed to BeginApply"
                         Err.Clear
                    End If

                    ' Add the ClientID so the lock allows us to apply the setting
                    SValueSet.Add "ClientSetId", ClientID

               end if
               
               ' We need to pass over errors in this block since we dont want to fail 
               ' out of the script before Apply has been called.  
               on error resume next

                    set retObject = adapter.ExecMethod_(sMethodName, InParams, 0 , SValueSet)                              
               on error goto 0

               if bDoApply then
                    ' Try to apply the setting
                    if Apply (hWMIServices, ClientID, sResult) = false  then 
                         ' We failed, update the sResult telling where 
                         ' we failed and stop looping
                         sResult = "Failed to apply setting"
                         Err.Clear
                    end if
               end if     
          end if

          if IsNothing(retObject) then
               sResult = "Method not found: " & sMethodName
          end if
          
          set ExecuteMethodOnAdapter = retObject
          
     end function  

     
'===================================================
'  Function : Push
'   Purpose : Add an element to an existing array
' Arguments :  1. Name of the array to receive new value
'              2. New value to be added to the array
'   Returns : Nothing
'     Notes : The array that is passed in must be a dynamic size
'===================================================
   Function Push (byref ArrayRef, byval NewValue)
      'turn off errors - this suppresses some VB errors when indexing empty arrays
      On Error Resume Next
      ' Get array size
      Dim UpperBound : UpperBound = UBound(ArrayRef)
      ' If array has no elements
      If UpperBound = ""  Then
         ' Redim for 1 element
         Redim ArrayRef (0)
         ' Assign passed value
         ArrayRef(0) = NewValue
      Else
         ' Redim but preserve contents
         Redim Preserve ArrayRef (UpperBound + 1)
         ' Assign passed value
         ArrayRef(UpperBound + 1) = NewValue
      End If
      Err.Clear
   End Function

'===================================================
'  Function : PushObject
'   Purpose : Add an element to an existing array
' Arguments :  1. Name of the array to receive new value
'              2. New value to be added to the array
'   Returns : Nothing
'     Notes : The array that is passed in must be a dynamic size
'===================================================
   Function PushObject (byref ArrayRef, byval NewValue)
      'turn off errors - this suppresses some VB errors when indexing empty arrays
      On Error Resume Next
      ' Get array size
      Dim UpperBound : UpperBound = UBound(ArrayRef)
      ' If array has no elements
      If UpperBound = ""  Then
         ' Redim for 1 element
         Redim ArrayRef (0)
         ' Assign passed value
         set ArrayRef(0) = NewValue
      Else
         ' Redim but preserve contents
         Redim Preserve ArrayRef (UpperBound + 1)
         ' Assign passed value
         set ArrayRef(UpperBound + 1) = NewValue
      End If
      Err.Clear
   End Function
  
'===================================================
'  Function : GetErr
'   Purpose : Returns information about the current Err object
' Arguments : None
'   Returns : Err information if there is an Err present
'     Notes : This can be safely appended to any status string since if there are no Err conditions, it
'             will return nothing
'===================================================
     Function GetErr ()
     
          If Err.Number <> 0 Then
               GetErr =  VbNewLine & " Error  " & Err.number & VbNewLine &_
                                                   "     >  " & Err.Description & VbNewLine &_ 
                                                   "     >  " & Err.Source
          Else
               GetErr = ""
          End If          
     
     End Function 

  '===================================================
     '     Class : cAdapters
     '   Purpose : This is a wrapper class for the class cDevice and stores information about local network adapters.
     '                    It was created for speed when working with remote computers. Manipulating adapters requires multiple
     '             queries to the WMI layer to return information. To avoid multiple WMI connection requests, this class
     '             caches all the adapter information into memory where it can be queried quickly.
     '             Example : you can query an adapter for multiple capabilities but have only really queried the system once.
     '     Notes : When displaying a list of adapters, invoke the Sort() function to re-order the local array
     '             This class also can be queried to find out the string equivalents for adapter capability IDs, using the
     '             property CapabilityString()
     '===================================================
     Class cAdapters
          
          private maAdapters()
          private mdCapabilityDescriptions
          
          '===================================================
          '  Function : Class_Initialize
          '   Purpose : Class constructor 
          '===================================================
          Private Sub Class_Initialize ()
               Set mdCapabilityDescriptions = CreateObject("Scripting.Dictionary")
          End Sub

          '===================================================
          '  Function : GetAdapterCapabilityDescriptions
          '   Purpose : Retrieves adapter capability numbers and descriptions from the qualifier for the .Capabilities parameter
          '             in the IANet_PhysicalEthernetAdapter class so class clients can resolve numbers to strings quickly.
          ' Arguments : 1) hWMIServices - a handle to a namespace which implements IANet_PhysicalEthernetAdapter
          '     Notes : Capability numbers and string descriptions are stored in the member dictionary
          '===================================================
          Private Function GetAdapterCapabilityDescriptions (hWMIServices)
               
               On Error Resume Next
               Dim objProp, objQual, objClass, i
          
               Set objClass = hWMIServices.Get("IANet_PhysicalEthernetAdapter", wbemFlagUseAmEndedQualIfiers) 'Query with amended qualifiers
               
               'Iterate class properties looking for "Capabilities"
               for Each objProp in objClass.Properties_
                    If objProp.Name = "Capabilities" Then
                         'Iterate property qualifiers looking for "Values"
                         For Each objQual in objProp.Qualifiers_
                              If objQual.Name = "Values" Then
                                   'Iterate the Values array, saving indexes and string values to member dictionary
                                   For i = 0 To Ubound(objQual)
                                        mdCapabilityDescriptions.Add i, objQual(i)
                                   Next
                              End If
                         Next
                    End If
               Next
               
          End Function
          
          '===================================================
          '  Property : Count
          '   Returns : Comma delimited string or empty string (If array is empty)
          '===================================================
          Public Property Get AdapterCount ()
               'Requesting Ubound() on empty arrays throws Err - so handle it here and clear it later
               On Error Resume Next
               ' we have to add 1 since Ubound returns the highest valid index
               AdapterCount = Ubound(maAdapters) + 1
               If Err.number <> 0 Then
                    AdapterCount = 0
               End If
               Err.Clear
          End Property

          '===================================================
          '  Property : CapabilityString 
          '   Returns : Returns the capability string for a capability ID
          '===================================================
          Public Property Get CapabilityString (iID)
               If mdCapabilityDescriptions.Exists(iID) Then
                    CapabilityString = mdCapabilityDescriptions.Item(iID)
               Else
                    CapabilityString = "UNKNOWN"
               End If
          End Property

          '===================================================
          '  Property : Name
          '   Returns : Returns name of adapter with index of iIndex 
          '===================================================
          Public Property Get Name (iIndex)
               'Requesting Ubound() on empty arrays throws Err - so handle it here and clear it later
               On Error Resume Next
               If Cint(iIndex) <= Ubound(maAdapters) Then
                    Name = maAdapters(Cstr(iIndex)).Name
               Else
                    Name = ""
               End If
               Err.Clear
          End Property

          '===================================================
          '  Property : Path
          '   Returns : Returns path of adapter with index of iIndex 
          '===================================================
          Public Property Get Path (iIndex)
               'Requesting Ubound() on empty arrays throws Err - so handle it here and clear it later
               On Error Resume Next
               If Cint(iIndex) <= Ubound(maAdapters) Then
                    Path = maAdapters(Cstr(iIndex)).Path
               Else
                    Path = ""
               End If
               Err.Clear
          End Property     
          
          '===================================================
          '  Property : DeviceID
          '   Returns : Returns DeviceID of adapter with index of iIndex 
          '===================================================
          Public Property Get DeviceID (iIndex)
               'Requesting Ubound() on empty arrays throws Err - so handle it here and clear it later
               On Error Resume Next
               If Cint(iIndex) <= Ubound(maAdapters) Then
                    DeviceID = maAdapters(Cstr(iIndex)).DeviceID
               Else
                    DeviceID = ""
               End If
               Err.Clear
          End Property     
          
          '===================================================
          '  Property : PCIDeviceID
          '   Returns : Returns PCIDeviceID of adapter with index of iIndex 
          '===================================================
          Public Property Get PCIDeviceID (iIndex)
               'Requesting Ubound() on empty arrays throws Err - so handle it here and clear it later
               On Error Resume Next
               If Cint(iIndex) <= Ubound(maAdapters) Then
                    PCIDeviceID = maAdapters(Cstr(iIndex)).PCIDeviceID
               Else
                    PCIDeviceID = ""
               End If
               Err.Clear
          End Property     
          
          '===================================================
          '  Property : GetAdapterInstance
          '   Returns : Returns CDevice instance of adapter with index of iIndex 
          '===================================================
          public Property Get GetAdapterInstance(byval iIndex)
               if (Cint(iIndex) >= 0) AND (Cint(iIndex) <= AdapterCount) then
                    set GetAdapterInstance = maAdapters(iIndex)
               else
                    set GetAdapterInstance = nothing
               end if 
          end Property

          '===================================================
          '  Function : HasCapability
          '   Purpose : Queries saved adapter properties to see if they support a particular capability 
          ' Arguments : 1) iIndex (int) - the index of the adapter to query
          '             2) iCapability (int) - the capability to query
          '   Returns : True if the capability exists, False otherwise
          '             This class' Enumerate function stores capabilities in the cDevice.maData parameter
          '             so this same member variable must be iterated when searching for capabilities.
          '===================================================
          Public Function HasCapability (byval iIndex, byval iCapability)
               If maAdapters(iIndex).Contains(iCapability) Then
                    HasCapability = true
                    Exit Function
               End If
               HasCapability = false
          End Function

          '===================================================
          '  Function : GetSupportedTeamModes
          '   Purpose : Checks the adapter for all team mode capabilities
          ' Arguments : 1) iIndex (int) - the index of the adapter to query
          '             
          '   Returns : An array filled with all supported modes, 'nothing' otherwise
          '===================================================
          Public Function GetSupportedTeamModes(byval iIndex)
               dim SupportedTeamModes()
               if HasCapability(iIndex, TEAMING_MODE_AFT) then
                    push SupportedTeamModes, TEAMING_MODE_AFT
               end if

               if HasCapability(iIndex, TEAMING_MODE_ALB) then
                    push SupportedTeamModes, TEAMING_MODE_ALB
               end if

               if HasCapability(iIndex, TEAMING_MODE_GEC) then
                    push SupportedTeamModes, TEAMING_MODE_GEC
               end if

               if HasCapability(iIndex, TEAMING_MODE_FEC) then
                    push SupportedTeamModes, TEAMING_MODE_FEC
               end if

               if HasCapability(iIndex, TEAMING_MODE_8023AD) then
                    push SupportedTeamModes, TEAMING_MODE_8023AD
               end if

               if HasCapability(iIndex, TEAMING_MODE_SFT) then
                    push SupportedTeamModes, TEAMING_MODE_SFT
               end if

               if HasCapability(iIndex, TEAMING_MODE_VMLB) then
                    push SupportedTeamModes, TEAMING_MODE_VMLB
               end if

               ' if SupportedTeamModes is an empty array, ubound will crash 
               ' so we have to turn off error handling
               on error resume next
                    err.clear
                    dim numberOfTeamModes : numberOfTeamModes = ubound(SupportedTeamModes)
                    ' if it crashed, se numberOfTeamModes to -1 so it sets the function return to nothing
                    if err.number <> 0 then
                         numberOfTeamModes = -1
                         err.clear
                    end if
               ' Now that were done with the handling section
               ' we can turn error handling back on
               on error goto 0

               ' if there are any supported team modes, return the array.
               ' otherwise return nothing.
               if numberOfTeamModes >= 0 then 
                    GetSupportedTeamModes = SupportedTeamModes
               else
                    GetSupportedTeamModes = nothing
               end if
               
          end function          

          '===================================================
          '  Function : Enumerate
          '   Purpose : Queries instances IANet_PhysicalEthernetAdapter and saves the information. 
          ' Arguments : 1) a WMI services handle to a namespace which defines IANet_PhysicalEthernetAdapter
          '             2) sReturn (string) - if the function fails, this string will contain reason   
          '   Returns : True If the enumeration occured, False otherwise
          '     Notes : The handle hWMIServices can be connected to any machine (local or remote), but it must be a
          '             a valid connection. Without this, the function will not work.
          '===================================================
          public function Enumerate( byref hWMIServices, byref sReturn )     

               'Set Error Handling and Err Status
   '                 On Error Resume Next
                    Err.Clear
               
               'Erase the existing array
                    Erase maAdapters
                    
               'Get the Capability Descriptions only if they are not defined
               'Capability IDs are static regardless of configuration; therefore, there is only a need to enumerate them once
               'This way, a client can call Enumerate( ) as often as they want but only suffer the overhead of querying
               'the capability description strings on the first call.
                    If mdCapabilityDescriptions.Count = 0 Then
                         GetAdapterCapabilityDescriptions hWMIServices
                    End If

               'Enumerate instances of IANet_PhysicalEthernetAdapter using the passed in Wbem handle
                    Dim wbemObjectSet 
                    Set wbemObjectSet = hWMIServices.ExecQuery("Select * from IANet_PhysicalEthernetAdapter WHERE StatusInfo = '3'")

               'Handle empty collections
                    If Not IsNumeric(wbemObjectSet.Count) Then
                         'Append Err information if Err was thrown, else GetErr adds nothing
                         sReturn = "Unable to query instances of IANet_PhysicalEthernetAdapter" & GetErr
                         Enumerate = False
                         Exit Function
                    end if
               
               'Redimension the array to match number of returned instances
               ' - arrays are 0 indexed so we must remove 1 from the total count
                    Redim maAdapters (wbemObjectSet.count - 1)
               
               'Init array indexer
                    Dim i : i = 0
               
                    Dim wbemObject
                    for each wbemObject in wbemObjectSet
                         'Create a new class instance of Adapter
                              Set maAdapters(i) = New cDevice
                         'Save the instance
                              maAdapters(i).DeviceInstance = wbemObject
                         'Save the path
                              maAdapters(i).Path = wbemObject.Path_
                         'Save the name
                              maAdapters(i).Name = wbemObject.Name
                         'Store adapter capabilities
                              Dim elem
                              For each elem in wbemObject.Capabilities
                                   maAdapters(i).Push elem
                              Next
                         'Sort the Capabilities that were just pushed into the array
                              maAdapters(i).SortData()
                              
                         'Save Device ID
                              maAdapters(i).DeviceID = wbemObject.DeviceID
                         'Save PCI Device ID
                              maAdapters(i).PCIDeviceID = wbemObject.PCIDeviceID
                         'Increment array index          
                              i = i + 1
                    next
                    
                    Sort()
                    Enumerate = True
                    
          End Function

          '===================================================
          '  Function : Sort
          '   Purpose : Sorts the adapter array on .DeviceID
          '   Returns : Nothing
          '     Notes : This function is used to provide a uniform order of adapters
          '             to users so they can enter adapter indexes.
          '                      Do not sort on adapter name - teaming operations will
          '             change the adapter name and skew the sort order
          '===================================================
          Public Function Sort()
               'Requesting Ubound() on empty arrays throws Err - so handle it here and clear it later
               On Error Resume Next
               Dim i , j , temp
               For i = Ubound(maAdapters) - 1 to 0 Step - 1 
                    For j = 0 to i
                         If maAdapters(j).DeviceID > maAdapters(j+1).DeviceID Then
                              Set temp = maAdapters(j+1)
                              Set maAdapters(j+1) = maAdapters(j)
                              Set maAdapters(j) = temp
                         End If     
                    Next
               Next
               Err.Clear
          End Function
          
          '* debug only *
          Public Sub PrintAdapters()
               On Error Resume Next
               Dim i
               For i = 0  to Ubound(maAdapters)
                    Wscript.Echo "maAdapters [" & CStr(i) & "] " 
                    maAdapters(i).Print_
               Next
               Err.Clear
          End Sub

          '* debug only *
          Public Sub PrintCapabilityDescriptions()
               'On Error Resume Next
               Dim aKeys
               aKeys = mdCapabilityDescriptions.Keys
               Wscript.Echo "Contents of dictionary mdCapabilityDescriptions:"
               For i = 0 to Ubound (aKeys)
                    Wscript.Echo aKeys(i) & " <-> " & mdCapabilityDescriptions.Item(aKeys(i))
               Next
               Err.Clear
          End Sub
     
     End Class

     '===================================================
     '     Class : cDevice
     '   Purpose : A generic data class which can be used to save information about any
     '             device which may be found in DMiX (Team, Adapter, VLAN, etc).
     '     Notes : This class assumes basic properties about DMiX devices in WMI,
     '             specIfically that it has a Name, a Path, and additional data
     '             which may need to be stored.
     '             This class can be extEnded in the future to include additional
     '             functions and properties where needed. Existing classes which 
     '             implement it will not be impacted by these changes.
     '===================================================
     Class cDevice
     
          private msName          
          private msPath          
          private msData     
          private msDeviceID     
          private msPCIDeviceID
          private maData()
          private moDeviceInstance
          
          'Default constructor
          Private Sub Class_Initialize
               msPath = ""
               msName = ""
               msData = ""
               msDeviceID = ""
               msPCIDeviceID = ""
          End Sub

          Public Property Get DeviceInstance()
               set DeviceInstance = moDeviceInstance
          end property

          Public Property Let DeviceInstance(value)
               if not IsNothing(value) then
                    set moDeviceInstance = value
               else
                    set moDeviceInstance = nothing
               end if
          end property
          
          Public Property Get Name ()
               Name = msName
          End Property     

          Public Property Let Name (value)
               msName = Cstr(value)
          End Property     
     
          Public Property Get Path ()
               Path = msPath
          End Property     

          Public Property Let Path (value)
               msPath = Cstr(value)
          End Property     
     
          Public Property Get Data ()
               Data = msData
          End Property     

          Public Property Let Data (value)
               msData = Cstr(value)
          End Property     

          Public Property Get DataValueAt(value)
               if value >=0 AND value <= DataCount then
                    DataValueAt = maData(value)
               end if
          end Property
     
          Public Property Get DeviceID ()
               DeviceID = msDeviceID
          End Property     

          Public Property Let DeviceID (value)
               msDeviceID = Cstr(value)
          End Property

          Public Property Get PCIDeviceID ()
               PCIDeviceID = msPCIDeviceID
          End Property     

          Public Property Let PCIDeviceID (value)
               msPCIDeviceID = Cstr(value)
          End Property          

          Public Property Get DataCount ()
               On Error Resume Next
               Err.Clear
               DataCount = Ubound(maData)
               If Err.number <> 0 Then
                    DataCount = 0
                    Err.Clear
               End If
          End Property     

          Public Function Push (byval value)
           On Error Resume Next
             Dim UpperBound : UpperBound = UBound(maData)
               If UpperBound = ""  Then
                    Redim maData (0)
                    maData(0) = value
               Else
                    Redim Preserve maData (UpperBound + 1)
                    maData(UpperBound + 1) = value
               End If
               Err.Clear
          End Function
          
          Public Sub Clear ()
               Erase maData
          End Sub
          
          Public Function Contains(value)
               On Error Resume Next     
               Dim i
               for i = 0 to Ubound (maData)
                    if maData(i) = value then
                         Contains = true
                         Exit Function
                    end if
               next
               Contains = false
               Err.Clear
          End Function

          Public Function SortData()
               'Requesting Ubound() on empty arrays throws Err - so handle it here and clear it later
               On Error Resume Next
               Dim i , j , temp
               dim count : count = Ubound(maData) - 1
               
               For i = count to 0 Step - 1 
                    For j = 0 to i
                         If CInt(maData(j)) > CInt(maData(j+1)) Then
                              temp = maData(j+1)
                              maData(j+1) = maData(j)
                              maData(j) = temp
                         End If     
                    Next
               Next

               Err.Clear
          End Function
          
          ' * Debug only *
          Public Function Print_()
               
               Dim i, elem
               Wscript.Echo  VbNewLine & "Name = " & msName
               Wscript.Echo  "Path = " & msPath
               Wscript.Echo  "DeviceID = " & msDeviceID
               Wscript.Echo  "PCIDeviceID = " & msPCIDeviceID
               Wscript.Echo  "Data Count = " & DataCount
               Wscript.Echo  "Data Contents : "
               for each elem in maData
                    Wscript.Echo elem
               Next
          End Function
          
     End Class

     function IsHexString(byVal sSettingValue)
          dim lowerA,lowerF, upperA, upperF, zero, nine

          lowerA = Int(Asc("a"))
          lowerF = Int(Asc("f"))
          upperA = Int(Asc("A"))
          upperF = Int(Asc("F"))
          zero = Int(Asc("0"))
          nine = Int(Asc("9"))     

          dim bIsHex
          bIsHex = true

          dim i, currentCharAsInt
          for i = 0 to len(sSettingValue)-1
               currentCharAsInt = Int(Asc(Left(sSettingValue,1)))
               
               if not (lowerA <= currentCharAsInt AND lowerF >= currentCharAsInt) then
                    if not (upperA <= currentCharAsInt AND upperF >= currentCharAsInt) then
                         if not (zero <= currentCharAsInt AND nine >= currentCharAsInt) then
                              bIsHex = false
                         end if
                    end if
               end if
               
               sSettingValue = Right(sSettingValue, len(sSettingValue)-1)
          next

          IsHexString = bIsHex
     end function
     
     '===================================================
     '  Function : ConvertCollectionToDelimitedString
     '   Purpose : Converts elements of a collection to a delimited string
     ' Arguments : 1) the collection to be saved
     '             2) a string delimeter
     '   Returns : the delimited string
     '     Notes : The collection should contain elements which can be converted
     '             safely to a string. Thus, only basic data types can be used.
     '===================================================
     Function ConvertCollectionToDelimitedString (byref cCollection, byval sDelimeter)
          
          On Error Resume Next
          Dim cElement, sReturn
          
          for each cElement in cCollection
               sReturn = sReturn & CStr(cElement) & sDelimeter
          next
          
          'trim last delimeter
          If not IsNull(sReturn) Then
               ConvertCollectionToDelimitedString = Left(sReturn, Len(sReturn) - Len(sDelimeter))
          Else
               ConvertCollectionToDelimitedString = ""
          End IF
          
          Err.Clear
          
     End Function

     '===================================================
     '  Function : CountIntegersToString
     '   Purpose : Copies all numbers between two integers into a delimited string
     ' Arguments : 1) the starting number
     '             2) the ending number
     '             3) the delimeter
     '   Returns : the delimited string or "ERROR"
     '     Notes : 
     '===================================================
     Function CountIntegersToString (iStart, iStop, sDelimeter)
          
          If iStart > iStop OR _
               IsNumeric (iStart) = false OR _
               IsNumeric (iStop) = false Then
               CountIntegersToString = "ERROR"
               Exit Function
          End If
          
          Dim i, sReturn
          
          For i = iStart to iStop
               sReturn = sReturn & CStr(i)
               if i <> iStop then
                    sReturn = sReturn & sDelimeter
               end if
          Next
          
          CountIntegersToString = sReturn
          
     End Function
     
     '===================================================
     '  Function : ShiftIntStringDown
     '   Purpose : Takes a comma delimited string of integers and shifts every integer down 1
     ' Arguments : 1) the source string
     '   Returns : the new string
     '     Notes : this will not affect strings without commas or non-integer string elements
     '===================================================
     Function ShiftIntStringDown (sOriginal)
     
          On Error Resume Next
          'Split string into an array
          Dim i, aArray : aArray = Split (sOriginal, ",")
          
          For i = 0 to Ubound(aArray)
               If IsNumeric(aArray(i)) Then
                    aArray(i) = CStr(Cint(aArray(i)) - 1)
               End if
          Next
          
          ShiftIntStringDown = Join(aArray , ",")
          Err.Clear
          
     End Function

'===================================================
'  Function : CreateTeam
'   Purpose : Creates an ANS Team
' Arguments : 1. hWMIServices (object) WbemServices handle to a root\Intelncs2 namespace
'             2. MemberArray (Array of string) Array holding the *PATH* of the adapters to be added
'             3. TeamCode (int) number code for the team to be created
'             4. TeamName (string) name of the team to be created
'             5. MFOEnable (bool) whether or not to enable MFO
'             6. sReturn (string) if the function returns False, this string will contain the reason
'   Returns : Returns True if the team request passed, False otherwise
'
'===================================================
   Public Function CreateTeam (byref hWMIServices, byref aMemberArray, byval iTeamCode, byval sTeamName, byval bMFOEnable, byref sReturn)
          
          Dim FuncName : FuncName = "CreateTeam()"
          Dim iClientSetHandle
          Err.Clear

     '===================================================
     '  Validate Function Arguments
     '===================================================
          If Not IsObject (hWMIServices) or IsNull(hWMIServices) or IsEmpty (hWMIServices) Then
               sReturn =  "FAIL :  invalid WMI services handle passed to " & FuncName
               CreateTeam = False
               Exit Function
          End If     

          If Not IsArray (aMemberArray) Then
               sReturn = "FAIL :  invalid array passed to " & FuncName
               CreateTeam = False
               Exit Function
          End If     

          If Not IsNumeric(iTeamCode) OR _
               iTeamCode < 0 OR _
               iTeamCode > 6 OR _
               iTeamCode = 3 Then
               sReturn = "FAIL :  invalid team code passed to " & FuncName
               CreateTeam = False
               Exit Function
          End If     
      
          If Len(sTeamName) <= 0 Then
               sReturn = "FAIL :  invalid team name passed to " & FuncName
               CreateTeam = False
               Exit Function
          End If     

          ' Check that any of the specified adapters aren't already in a team
          ' Loop through the passed in adapters
          dim counter
          for counter = 0 to ubound(aMemberArray)
               ' try to get the instance of the adapter in IANet_TeamedMemberAdapters
               dim AdapterCollection, AdapterInstance
               set AdapterCollection = ReferencesOfQueryWmiClass(hWMIServices, aMemberArray(counter), "ResultClass = IANet_TeamedMemberAdapter")
               dim AdapterName : AdapterName = ""
               for each AdapterInstance in AdapterCollection
                    ' the adapter is in a team, now get the adapter name so we can report back to the calling function
                    dim adapter, adapCol
                    set adapCol = SelectQueryWmiClass(hWMIServices, "*", "IANet_PhysicalEthernetAdapter", "")

                    ' Loop through each adapter until we have a "PATH" match
                    for each adapter in adapCol
                         if adapter.Path_.Path = aMemberArray(counter) then
                              ' Set adapter name to the caption
                              AdapterName = adapter.Caption
                         end if     
                    next

                    ' Set the return string to say the adapter is already in a team
                    sReturn = AdapterName & " is already a member of another team."          

                    'Return false and exit the function now.
                    CreateTeam = False
                    Exit Function                    
               next
          next 
          
     '===================================================
     '  Build Inparameters for function call
     '===================================================
          Dim oValueSet : Set oValueSet = CreateObject("WbemScripting.SWbemNamedValueSet")
          oValueSet.Add "ClientSetId", iClientSetHandle

     'Get the definition of the IANet_TeamOfAdapters class
          Dim IANet_TeamOfAdapters_Def
          Set IANet_TeamOfAdapters_Def = hWMIServices.Get("IANet_TeamOfAdapters")

     ' Check definition was retrieved
          If IsNothing(IANet_TeamOfAdapters_Def) Then
               sReturn = "FAIL : unable to obtain definition for IANet_TeamOfAdapters" & GetErr
               CreateTeam = False
               Err.Clear
               Exit Function
          End If

     'Create the InParameters
          Dim InParameterObj 
          Set InParameterObj = IANet_TeamOfAdapters_Def.Methods_.Item("CreateTeam").InParameters.SpawnInstance_()

     'Check a valid object was returned
          If IsNothing(InParameterObj) Then
               sReturn = "FAIL : unable to spawn inparams of CreateTeam function" & GetErr
               Err.Clear
               CreateTeam = False
               Exit Function
          End If

     'Fill in function arguments
          InParameterObj.Adapters = aMemberArray
          InParameterObj.TeamingMode = iTeamCode
          InParameterObj.TeamName = sTeamName
          InParameterObj.MFOEnable = bMFOEnable
               
     'Exit if there were any errors setting in params
          If Err.Number <> 0 Then
               sReturn = "FAIL :  an error occured while setting CreateTeam in params " & GetErr
               Err.Clear
               CreateTeam = false
               Exit Function
          End If

          dim ClientID
          dim bSuccess : bSuccess = true
     '===================================================
     ' Obtain Session Lock
     '===================================================
          ' Do a BeginApply to acquire a lock in Middleware to prepare to write a setting
          If BeginApply(hWMIServices, ClientID, sReturn) = False Then
               ' We failed, set the success bool to false and update 
               ' the sResult telling where we failed and stop looping
               Err.Clear
               CreateTeam = false
               exit function
          End If

          on error resume next
          
          ' Add the ClientID so the lock allows us to apply the setting
          oValueSet.Add "ClientSetId", ClientID

          ' Update the setting to what we want it to be
          Dim OutParameterObj
          Set OutParameterObj = IANet_TeamOfAdapters_Def.ExecMethod_("CreateTeam", InParameterObj, 0, oValueSet)

          ' Investigate returned SWbemObject
          if not IsNothing(OutParameterObj) then
               if OutParameterObj.TeamPath = "" then
                    sReturn = "FAIL : teaming request failed" & GetErr
                    bSuccess = false
                    Err.Clear
               else     
                    bSuccess = true
               End If
          else 
               bSuccess = false
          end if     

          on error goto 0 

          ' Try to apply the setting
          if Apply (hWMIServices, ClientID, sReturn) = false  then 
               ' We failed, set the success bool to false and update 
               ' the sResult telling where we failed and stop looping
               Err.Clear
               CreateTeam = false
               exit function
          end if

          CreateTeam = bSuccess
   End Function
         
'===================================================
'  Function : BeginApply
'   Purpose : Opens a session lock with the DMiX software layer by invoking the BeginApply() function of the
'             root\Intelncs2\IANet_NetService class.
' Arguments : 1) WbemServices - swbemservices handle which represents an active connection
'             2) ClientSetID - variable to receive the client set ID
'             3) sReturn - if the function returns False, this string will contain the reason
'
'   Returns : True if successful, False if not
'     Notes : 
'===================================================
   Function BeginApply(byref WbemServices, byref ClientSetHandle, byref sReturn)
                      
      Err.Clear
          On Error Resume Next
          
      Dim NetServiceObject
      Dim colNetServiceObject : Set colNetServiceObject = WbemServices.ExecQuery("Select * from IANet_NetService", , wbemFlagReturnImmediately)
      
      WbemServices.Security_.Privileges.AddAsString "SeLoadDriverPrivilege", True

          If IsObject(colNetServiceObject) Then
               For Each NetServiceObject In colNetServiceObject
                    Dim objReturn : Set objReturn = NetServiceObject.ExecMethod_("BeginApply")  
                    If objReturn.ReturnValue = 0 Then
                         ClientSetHandle = Cint(objReturn.ClientSetHandle)
                         BeginApply = True
                    Else
                         sReturn =  "Unable to establish to obtain client lock ID" & GetErr
                         BeginApply = False
                         Err.Clear
                    End If     
               Next
          Else
               sReturn =  "Unable to obtain instances of IANet_NetService " & GetErr
               BeginApply = False
               Err.Clear
          End If

   End Function

'===================================================
'  Function : Apply
'   Purpose : Applies requested software layer changes with the supplied client lock ID.
' Arguments : 1) WbemServices - swbemservices handle which represents an active connection
'             2) ClientSetID - variable to receive the client set ID
'             3) sReturn - if the function returns False, this string will contain reason
'
'   Returns : True if successful, False if not
'     Notes : 
'===================================================
   Function Apply(byref WbemServices, byval ClientSetHandle, byref sReturn)
                         
          Err.Clear
          On Error Resume Next

      Dim NetServiceObject
      Dim colNetServiceObject : Set colNetServiceObject = WbemServices.ExecQuery("Select * from IANet_NetService", , wbemFlagReturnImmediately)
      
      If IsObject(colNetServiceObject) Then
               For Each NetServiceObject In colNetServiceObject
                    'Spawn IN parameters for 'Apply'
                         Dim objInParams : Set objInParams = NetServiceObject.Methods_.Item("Apply").InParameters.SpawnInstance_()
                    'Handle failure to spawn in params
                         If Not IsObject (objInParams) Then
                              sReturn = "Unable to spawn in parameters of Apply() method"
                              Apply = False
                              Exit Function
                         End If
                    'Set ClientSetHandle
                         objInParams.ClientSetHandle = ClientSetHandle
                    'Invoke method         
                       Dim objReturn : Set objReturn = NetServiceObject.ExecMethod_("Apply", objInParams)
                    'Evaluate return codes
                         If objReturn.ReturnValue = 0 Then
                              Apply = True
                              'Evaluate FollowUpAction (0 = no reboot, 1 = reboot)
                              If objReturn.FollowUpAction = 1 Then
                                   Wscript.Echo "A reboot is required"
                              End If
                         Else
                              Apply = False
                              sReturn = "Failed to apply changes"
                         End If     
               Next
           Else
               sReturn = "Unable to obtain instances of IANet_NetService" & GetErr
               Err.Clear
               Apply = False
          End If

   End Function
        
'===================================================
'  Function : IsNothing
'   Purpose : Provides a single way to determine if multiple variable types are empty/nothing/null
' Arguments : Value - the object to evaluate
'   Returns : True (if the object is empty/nothing/null); or false
'     Notes : Empty == Uninitialized, Null == Null. Nothing == for objects only, same as Empty 
'===================================================
Function IsNothing(Value)

		IsNothing = False

		If IsEmpty(Value) Then
			IsNothing = True
			Exit Function
		End If

		If IsNull(Value) Then
			IsNothing = True
			Exit Function
		End If

		If IsObject(Value) Then
			If Value Is Nothing Then
				IsNothing = True
				Exit Function
			End If
		End If	
			
End Function

'===================================================
'  Function : VERIFY
'   Purpose : Evaluates a passed in condition to see if it is True or False. VBScript does not have VERIFY capability so this 
'             function attempts to fill that role.
' Arguments : vCondition (variant) - the condition which will evaluate to True or False
'             sHint (string) - a message which help trace back to the location of the assert
'   Returns : True if the VERIFY is true, False for everything else.
'     Notes : 
'===================================================
Function VERIFY (byval vCondition, sHint)

	Dim bCondition : bCondition = CBool (vCondition)
	If Not bCondition Then DbgPrint "VERIFY Failed! " & sHint
	VERIFY = bCondition

End Function

'===================================================
'       Sub : DbgPrint 
'   Purpose : Accepts a user string to be printed to debug, checks the global CONST DEBUG_MODE, and if that is true,
'             prints the statement out to the screen.
' Arguments : Debug (variant) - the debug statement
'     Notes : All passed in parameters are converted to a CStr
'===================================================
Sub DbgPrint (Debug)

	If DEBUG_MODE Then
		Wscript.Echo "|Debug| " + CStr(Debug)
	End If
	
End Sub

'===================================================
'  Function : IsCScript
'   Purpose : Detects whether the script engine is Cscript or not
' Arguments : None
'     Notes : 
'===================================================
Function IsCScript
	IsCScript = Instr(lcase(wscript.FullName), "cscript") > 0
End Function






'===================================================
'  Function : IdentifyAdapter
'   Purpose : Calls the corresponding method in the IANet_PhysicalEthernetAdapter
' Arguments :  1. a variable to receive a SwbemServices object
'              2. the adapter instance
'              3. the number of seconds for the adapter to blink
'          
'   Returns : True (if ther call was successful); or false
' 
'              
'===================================================
Function IdentifyAdapter(byRef hWMIService, byVal oAdapter, byVal dNoOfSecs, byref sResult)
	   dim IANet_PhysicalEthernetAdapter, i
          dim bValidSetting : bValidSetting = false
          dim bValidValue : bValidValue = false          
          dim bSetSuccess : bSetSuccess = false

          ' Make sure the inputs are not null or blank values
          ' Failing any one of these will immediately return a failure
          
          ' Check the WMI handle
          if IsNothing(hWMIService) = true then
               IdentifyAdapter = false
               exit function
          end if

          ' Check the adapter object
          if IsNothing(oAdapter) = true then
               IdentifyAapter = false
               exit function
          end if
          
          ' Check the setting
          if (dNoOfSecs <= 0) = true then
               IdentifyAdapter = false
               exit function
          end if
          

          ' We made it this far, the inputs were all provided

          dim inParam
          Set inParam = oAdapter.DeviceInstance.Methods_.Item("IdentifyAdapter").InParameters
          inParam.nSeconds = dNoOfSecs
         

          dim retObject : set retObject = nothing
          set retObject = ExecuteMethodOnAdapter(hWMIService, oAdapter, "IdentifyAdapter", inParam, false, sResult)
          set IdentifyAdapter = retObject
          	

End Function






