?
Solved

SCCM PE HTA script SET env = CreateObject("Microsoft.SMS.TSEnvironment") variable undefined

Posted on 2009-05-06
2
Medium Priority
?
7,497 Views
Last Modified: 2013-11-21
SCCM PE HTA script SET env = CreateObject("Microsoft.SMS.TSEnvironment") variable undefinedBookmark:Question: I have two scripts I am testing in Vista PE on SCCM 2007 SP1 RC2.

Requirement is broken into two parts

PART 1: (this first script works fine on its own)
1) Recieve a variable from SCCM server (Desktop, Laptop, VMware)
Variable ---> machinetype = env("NCL-HIS_OSDMachineType")

2) HTA form has an input box for workstation name (this is recieved via wedge barcode scanner)

3) join SCCM Variable + input box to create the workstation name
workstation name ----> DESKTOP-1234567

PART 2:
Add the above code to the microsoft provided "Unknown workstations" HTA for pre-staging workstations

ISSUES
The first script (PART1) works fine, and sets "SET env = CreateObject("Microsoft.SMS.TSEnvironment") " with no issies.

I have then tried to added the working code from PART1 to the PART2, however, I am recieving the error "Variable is undefined: 'env' line 107.

I would like to receive some pointers on how to troubleshoot the error, or advice on what I'm doing wrong when adding the working code from Part1 to the Microsoft unknown workstation code.

NOTE:  The changes made to PART2 which are the components I have added from PART1, are enclosed in double tram lines of ****** as shown below.
'****************************************
'****************************************
***********************************
 PART 1 working code to join workstation type with BarcodeID
***********************************
<html>
  <head>
  <title>Workstation naming: Get BarcodeID and create workstation name- test</title>
  <hta:application
    id="NCL-HIS Workstation naming"
    applicationName="NCL-HIS Workstation naming"
    border="5pt"
    borderStyle="raised"
    caption="yes"
    maximizeButton="yes"
    minimizeButton="yes"
    showInTaskBar="yes"
    singleInstance="yes"
    sysMenu="yes"
    windowState="maximize"
  >
  <SCRIPT Language="VBScript">
  DIM computername    ' null initially. "MachineType + BarcodeID = OSDComputerName"
  DIM MachineType     ' passed from SCCM Task sequence and defines "Desktop or laptop or VMware"
  DIM BarcodeID       ' variable to recieve barcode from scanner or keyboard input
 
  'msgbox "Variables1" & VBCrlf & "ComputerName: " & computername & VBCrlf & "MachineType: " & MachineType & VBCrlf & "BarcodeID: " & BarcodeID
 
 Sub Window_OnLoad     'onload set the focus to the text box waiting to receive the barcode input
    	 BarcodeInputFromUser.focus
 End Sub
 
 Sub ClearTextBoxes    'clear text boxes after the barcode is scanned so it can be scanned again if required
    	  BarcodeInputFromUser.Value = "" 
 End Sub
 
 
 Sub WaitingForEnterKey   'This function waits for ENTER key from barcode reader or keyoard
                          'when ENTER key is received, the function "DoProcess" is called
      If Window.Event.KeyCode = 13 Then
            DoProcess
      End If
 End Sub
 
  SET env = CreateObject("Microsoft.SMS.TSEnvironment")
  'get the machine type from the Task Sequence to determin "Laptop, Desktop, or VMware" prefix
  machinetype = env("NCL-HIS_OSDMachineType")
  'msgbox "Variables2" & VBCrlf & "ComputerName: " & computername & VBCrlf & "MachineType: " & MachineType & VBCrlf & "BarcodeID: " & BarcodeID
 
 sub DoProcess
	' Get the barcode as scanned from the user and set as "BarcodeID"
	  BarcodeID = BarcodeInputFromUser.value
	  SET env = CreateObject("Microsoft.SMS.TSEnvironment")
	  machinetype = env("NCL-HIS_OSDMachineType")
 
	  env("OSDComputerName") = MachineType & "-" & BarcodeID
 
 
          'now update the elements displayed to the user
	  document.getElementById("NCL-HIS_OSDMachineType").innerHTML="NCL-HIS_OSDMachineType: " & machinetype
	  document.getElementById("BarcodeID").innerHTML="BarcodeID: " & BarcodeID
	  document.getElementById("OSDComputerName").innerHTML="OSDComputerName: " & env("OSDComputerName")
	  ClearTextBoxes
	  BarcodeInputFromUser.focus
 end sub
 
 
  </script>
  </head>
  <body>
   <body onkeypress='vbs:WaitingForEnterKey'>
    <p>NCL-HIS Workstation naming process</p>
     <p>Please afix assett tag to workstation, Then</p>
     <p>Scan the barcode</p>
      <input type=text id="BarcodeInputFromUser" name=BarcodeInputFromUser size=1><br /><br />
 
  <form>
     <input type="hidden" id="Process" onClick="self.DoProcess()" value="Process" enabled=no>
  </form>
 
<div id="NCL-HIS_OSDMachineType"> </div>
<div id="BarcodeID"> </div>
<div id="OSDComputerName"> </div>
 
  </body>
</html>
 
 
***********************************
 PART 2 Unknown workstation code with Env error
***********************************
<!--   
-----------------------------------------------------------------------
NCH-HIS Workstation naming test
Version 0.1a
Created By: Charles Judd (modified script from Microsoft)
 
Script useage:
	Where workstation has network connectivity
	Look for Workstation object on SCCM server
	Collect BarcodeID from Wasp Bacode Scanner
	Where Workstation object does not exist, create object and add to collection "NCL0000E"
	Where workstation does exist in SCCM, add Workstation to to collection "NCL0000E"
	Wait for 'add to collection' to succeed or fail
	Then move on and allow the workstation to build
-----------------------------------------------------------------------
-->
 
<!--
 This HTA application 
            creates a machine record for the unknown system that it is run on,
            adds the machine to the specified collection,
            sets Machine and Task Sequence variables.
 Usage:
     Run this HTA on the unknown system for which a machine record is to be created.
     mshta.exe UnknownSystem.HTA <Provider Machine Name>
                                 <Provider Site Code>
                                 <Collection ID to add the system to>
-->
 
<html>
<head>
<title>System Build Process: Add Workstation to SCCM Collection</title>
 
<HTA:APPLICATION ID="oHTA"
     APPLICATIONNAME="Unknown System"
     SCROLL="yes"
     SINGLEINSTANCE="yes"
     WINDOWSTATE="maximize"
     SYSMENU="yes"
>
 
<script language="vbscript">
 
' Making Option explicit to ensure that all the variables are declared before usage.
Option Explicit
 
' Global Constants.
' If this is true, the log is shown in the reverse chronological order 
' (the latest log entry at the top)in the UI.
' Set this to false if you want otherwise.
Const RECENTLOGONTOP = false
 
' Global Variables.
' Logging related variables.
Dim isLogHidden : isLogHidden = False
Dim logFileSystemObject : logFileSystemObject = Null
' Command line arguments.
Dim providerName, provSiteCode, collectionIDToAddTo
' SMS Provider namespace objects.
Dim smsSiteNamespace : smsSiteNamespace = Null
Dim isSMSSiteNamespaceSet : isSMSSiteNamespaceSet = False
Dim machineMACAddress, machineSMBIOSGuid
 
'****************************************
'****************************************
'BARCODE NAMING PROCESS VARIABLES
DIM FullComputername    ' null initially. "MachineType + BarcodeID = OSDComputerName"
DIM MachineType         ' passed from SCCM Task sequence and defines "Desktop or laptop or VMware"
DIM BarcodeID           ' variable to recieve barcode from scanner or keyboard input
'****************************************
'****************************************
 
 
' Subroutine that executes as soon as the window is loaded.
 
 
Sub Window_Onload
 
    ' Create the log file as the first step so that all the logs below are
    ' recorded in the UI and the file.
    CreateLogFile ()
      
    Log ("--------------------------------------------------------")
    providerName = "ED01SR918"
    Log ("Provider Machine Name:" & providerName)
    provSiteCode = "NCL"
    Log ("Site Code of the provider:" & provSiteCode)
    collectionIDToAddTo = "NCL0000E"
    Log ("Collection ID of the collection to add this System to:" & collectionIDToAddTo)
    
    ' Get the MAC and SMBIOS GUID of the system.
    Log ("--------------------------------------------------------")
    Log ("Getting the MAC address and SMBIOS GUID of the system")
    machineMACAddress = GetMACAddress ()
    machineSMBIOSGuid = GetSMBIOSGuid ()
    
    ' Ask the user to enter the input.
    Log ("--------------------------------------------------------")
    Log ("Please fill in the data in the UI and click the ""Add Machine Now"" button")
 
 
'****************************************
'****************************************
          'onload set the focus to the text box waiting to receive the barcode input
          BarcodeInputFromUser.focus
          msgbox "Variables1.0" & VBCrlf & "FullComputerName: " & FullComputerName & VBCrlf & "MachineType: " & MachineType & VBCrlf & "BarcodeID: " & BarcodeID
          SET env = CreateObject("Microsoft.SMS.TSEnvironment")
          'get the machine type from the Task Sequence to determin "Laptop, Desktop, or VMware" prefix
          machinetype = env("NCL-HIS_OSDMachineType")
          msgbox "Variables1.1" & VBCrlf & "FullComputerName: " & FullComputerName & VBCrlf & "MachineType: " & MachineType & VBCrlf & "BarcodeID: " & BarcodeID	
'****************************************
'****************************************
End Sub
 
' Function executed when the "Add Machine Now" button is clicked.
' Imports the machine, adds it to a collection, adds machine and Task sequence variables.
Function Main
    ' Variables used across functions.
    Dim computerName, providerAccount, providerPassword
    Dim returnVal
 
    ' Re-initialize some global variables (may be set from previous run)
    smsSiteNamespace = Null
    isSMSSiteNamespaceSet = False
 
    ' Get the input from the UI.
    computerName = GetComputerName 
    providerAccount = GetProviderAccount 
    providerPassword = GetProviderPassword 
 
    ' Validate the input.
    If computerName = "" Then
        Log ("The computer name entry is invalid. Please provide the required information.")
        Exit Function
    End If
    If providerAccount = "" Then
        Log ("The user account entry is invalid. Please provide the required information.")
        Exit Function
    End If
    
    ' Connect to the provider and set the Configuration Manager namespace objects.
    Log ("--------------------------------------------------------")
    Log ("Setting the Configuration Manager Namespace object variables" )
    returnVal = SetConfigMgrNamespaceObjects (provSiteCode, providerName, providerAccount, providerPassword)
    ' If the Configuration Manager namespace objects are not set, exit the script.
    If isSMSSiteNamespaceSet = False Then
        Log ("Failed to set the Configuration Manager Namespace objects.")
        ' Close the log file handle before exiting.
        logFileSystemObject.Close
        logFileSystemObject = null
        Main = 1
        Exit Function
    End If 
    
    ' Create the machine record and add it to a collection.
    Log ("--------------------------------------------------------")
    Log ("Importing this unknown system into Configuration Manager")
    ' Variable to store the ResourceID of this unknown system to be used in the functions later.
    Dim machineResourceID: machineResourceID = 0
    returnVal = CreateMachineRecord (computerName , machineSMBIOSGuid , machineMACAddress , collectionIDToAddTo, machineResourceID)
    If returnVal <> 0 Then
        Log ("Failed to create machine record with error: " & returnVal & ".")
        ' Close the log file handle before exiting.
        logFileSystemObject.Close
        logFileSystemObject = null        
        Main = returnVal
        Exit Function
    End If
    
    ' Add the machine to the collection.
    ' You may have a Task Sequence to deploy an Operating System advertised to this collection and 
    ' available on media and PXE.
    Log ("--------------------------------------------------------")
    Log ("Adding this machine to the specified collection")
    returnVal = AddMachineToCollection (machineResourceID, collectionIDToAddTo)
    If returnVal <> 0 Then
        Log ("Failed to add the machine to the collection with error: " & returnVal & ".")
        ' Close the log file handle before exiting.
        logFileSystemObject.Close
        logFileSystemObject = null        
        Main = returnVal
        Exit Function
    End If
        
    ' Configuration Manager might take some time till the machine shows up as part of the collection
    ' depending on the size of the site and the number of clients etc.
    ' Wait till the machine is part of the collection so that when this HTA is closed, the Task Sequence
    ' (if any) assigned to the collection (and available on media and PXE) starts.
    returnVal = VerifyCollectionForResource (collectionIDToAddTo, machineResourceID)
    If returnVal <> 0 Then
        Log ("The machine with Resource ID =" & machineResourceID & " is still not part of the" & " collection with Collection ID = " & collectionIDToAddTo)
        ' Close the log file handle before exiting.
        logFileSystemObject.Close
        logFileSystemObject = null        
        Main = returnVal
        Exit Function
    End If
    
    Log ("--------------------------------------------------------")
    Log ("Close this HTA application for any Task Sequences advertised to the Collection " & collectionIDToAddTo & " to execute")
End Function
 
' Show/Hide the log.
Function ShowHideLog()
    If isLogHidden = True Then
        isLogHidden = False
        logTextArea.style.display = "block"
        showHideLogButton.value = "Hide Log"
    Else
        isLogHidden = True
        logTextArea.style.display = "none"
        showHideLogButton.value = "Show Log"
    End If 
End Function
 
' Create/Open the log file.
Function CreateLogFile()
    ' Form the complete file path to save the log.
    Dim fileSystem, completeLogFilePath
    Set fileSystem = CreateObject ("Scripting.FileSystemObject")
    completeLogFilePath = fileSystem.GetAbsolutePathName (".") & "\HTAApplication.log"
 
    ' Create the file and write the log to it.
    ' ForAppending = 8
    Set logFileSystemObject = fileSystem.OpenTextFile (completeLogFilePath, 8, True)
    
    ' Set the return value to the log file path
    CreateLogFile = completeLogFilePath
End Function
 
' Logs the given input into the UI and the log file.
Function Log(logEntry)
    ' Prepend current time to the input log entry.
    Dim lineOfLog, consolidatedLog
    lineOfLog = Now & " - " & logEntry 
    
    ' If the log file is not created or opened, do it now.
    If (IsNull (logFileSystemObject) = True) Then
        Dim logFileName
        
        ' Update the UI log alone to say that the log file is being created.
        logTextArea.value = logTextArea.value & vbcrlf & "Creating the log file to store the logs"
        logFileName = CreateLogFile ()
        
        ' Update the UI log alone to say that the log file was successfully created.
        logTextArea.value = logTextArea.value & vbcrlf & "Successfully created the log file " & logFileName
    End If
    
    ' If the log file is created, add the log to the end of the log file.
    ' The log in the log file is always chronological, i.e. the latest log at the end of the file.
    If (IsNull (logFileSystemObject) = False) Then
        logFileSystemObject.WriteLine (lineOfLog)
    End If
    
    ' Add the log to the UI.
    ' If RECENTLOGONTOP is true, make the new entry to be the topmost one in the UI.
    If RECENTLOGONTOP = True Then
        consolidatedLog = lineOfLog & vbcrlf & logTextArea.value
    Else
        consolidatedLog = logTextArea.value & vbcrlf & lineOfLog
    End If
    logTextArea.value = consolidatedLog
    Log = consolidatedLog
End Function
 
' Create and set Configuration Manager provider objects.
Function SetConfigMgrNamespaceObjects(siteCode, providerName, providerAccount, providerPassword)
    Dim locator
    
    ' Check if the smsSiteNamespace is not previously set.
    If isSMSSiteNamespaceSet = False Then
        ' Connect to the SMS\Site_<Sitecode> namespace on the provider machine.
        Set locator = CreateObject ("WbemScripting.SWbemLocator")
        On Error Resume Next
        Set smsSiteNamespace = locator.ConnectServer (providerName, "root\sms\site_" & siteCode, providerAccount, providerPassword )
        If Err <> 0 Then
            Log ("Failed to connect to SMS provider. (" & Err.number & ")")
            LogExtendedError ()
            Exit Function
        End If
        On Error Goto 0
        
        ' Setting ImpersonationLevel = impersonate and AuthenticationLevel = PktPrivacy.
        smsSiteNamespace.Security_.ImpersonationLevel = 3
        smsSiteNamespace.Security_.AuthenticationLevel = 6
        Log ("Successfully connected to the SMS Provider on: " & providerName & " and set the Configuration Manager Namespace objects " & Err.number)
        isSMSSiteNamespaceSet = True
    Else
        Log ("Configuration Manager Namespace object variables are already set")
    End If
End Function
 
' Import the machine into Configuration Manager.
Function CreateMachineRecord(computerName, smBiosGuid, macAddress, collectionID, ByRef resourceID)
    On Error Resume Next    
    
    ' Get the parameters for the ImportMachineEntry method.
    Dim smsSite
    Set smsSite = smsSiteNamespace.Get ("SMS_Site")
    If Err <> 0 Then
        Log ("Failed to connect to SMS_Site object. (" & Err.number & ")")
        CreateMachineRecord = Err
        LogExtendedError ()
        Exit Function
    End If
    
    ' Create ImportMachineEntry method's input parameter instance.
    Dim inParam
    Set inParam = smsSite.Methods_("ImportMachineEntry").inParameters.SpawnInstance_()
    If Err <> 0 Then
        Log ("Failed to create ImportMachineEntry method's input parameter instance. (" & Err.number & ")")
        CreateMachineRecord = Err
        LogExtendedError ()
        Exit Function
    End If
    ' Set the input parameters.
    
    ' Set the machine name for this system.
    inParam.Properties_.item("NetBiosName") = computerName
    ' Set the SMBIOSGUID.
    inParam.Properties_.item("SMBIOSGUID") = smBiosGuid
    ' Set the MAC Address.
    inParam.Properties_.item("MACAddress") = macAddress
    ' Set OverwriteExistingRecord to false to not overwrite the existing entry in Configuration Manager.
    ' If the system is already known to Configuration Manager, then the record for this system will exist.
    inParam.Properties_.item("OverwriteExistingRecord") = False
    
    ' Execute the ImportMachineEntry method.
    Dim outParams
    Set outParams = smsSite.ExecMethod_("ImportMachineEntry", inParam) 
    If Err <> 0 Then
        Log ("Failed to add the machine """ & computerName & """. (" & Err.number & ")")
        CreateMachineRecord = Err
        LogExtendedError ()
        Exit Function
    End If
    On Error Goto 0
    
    ' Check the ImportMachineEntry method's return value.
    If outParams.Properties_.item("ReturnValue") <> 0 Then
        Log ("Failed to add " & computerName & ". (" & outParams.Properties_.item("ReturnValue") & ")")
        CreateMachineRecord = outParams.Properties_.item("ReturnValue")
        Exit Function
    End If
    
    ' Log success since the ReturnValue is 0.
    ' Verify if the system already exists in the Configuration Manager.
    If outParams.Properties_.item("MachineExists") = True Then
        ' This machine is already present.
        Log ("Machine with MAC: " & macAddress & " and SMBIOS GUID:" & smBiosGuid & " already exists in " & "Configuration Manager. Its Resource ID = " & outParams.Properties_.item("ResourceID"))
        
        ' Get the computer name by which this machine is present in Configuration Manager.
        Dim machineRecord
        Set machineRecord = smsSiteNamespace.Get ("SMS_R_System.ResourceId='" &_
                                                 outParams.Properties_.item("ResourceID") & "'")
        If Err <> 0 Then
            Log ("Failed to find machine with Resource ID " & outParams.Properties_.item("ResourceID") & ". (" & Err.number & ")")
            CreateMachineRecord = Err
            LogExtendedError ()
            Exit Function
        End If
        
        ' Get the machine name.
        Dim machineName 
        machineName = machineRecord.Properties_.item("Name")
        Log ("It exists with a computer name '" & machineName & "'")
    Else
        Log ("Successfully added machine '" & computerName & "'. Resource ID = " & outParams.Properties_.item("ResourceID"))
    End If
    
    ' Set the ByRef parameter resourceID.
    resourceID = outParams.Properties_.item("ResourceID")
 
    ' Set the return value.
    CreateMachineRecord = 0
End Function
 
 
' Add the machine to the specified collection.
Function AddMachineToCollection(resourceID, collectionID )
    On Error Resume Next
    
    ' Get the collection with the given collection ID.
    Dim collection
    Set collection = smsSiteNamespace.Get ("SMS_Collection.CollectionID='" & collectionID & "'")
    If Err <> 0 Then
        Log ("Failed to find collection " & collectionID & ". (" & Err.number & ")")
        AddMachineToCollection = Err
        LogExtendedError ()
        Exit Function
    End If
    
    ' Get the machine with the given resource ID.
    Dim machineRecord
    Set machineRecord = smsSiteNamespace.Get ("SMS_R_System.ResourceId='" & resourceID & "'")
    If Err <> 0 Then
        Log ("Failed to find machine with Resource ID " & resourceID & ". (" & Err.number & ")")
        AddMachineToCollection = Err
        LogExtendedError ()
        Exit Function
    End If
    
    ' Get the machine name and convert resourceID to an int to be used in further queries.
    Dim machineName
    machineName = machineRecord.Properties_.item("Name")
    'resourceID = CInt (resourceID)
      
    ' Setup the collection rule.
    Dim collectionRule 
    Set collectionRule = smsSiteNamespace.Get ("SMS_CollectionRuleDirect").SpawnInstance_()
    If Err <> 0 Then
        Log ("Failed to create a SMS_CollectionRuleDirect instance. (" & Err.number & ")")
        AddMachineToCollection = Err
        LogExtendedError ()
        Exit Function
    End If
    ' Set the collection rule properties.
    ' Setting the collection rule based on the system properties, hence ResourceClassName = "SMS_R_System".
    collectionRule.ResourceClassName = "SMS_R_System"
    ' Give the rule a name. Using the machine name itself here.
    collectionRule.RuleName = machineName
    ' Set the ResourceID to the resource ID of the machine.
    collectionRule.ResourceID = resourceID
   
    ' Execute the AddMembershipRule method to add the machine to the collection.
    Dim inParam, outParams
    Set inParam = collection.Methods_("AddMembershipRule").inParameters.SpawnInstance_()
    ' Set the input parameters.
    inParam.Properties_.item("collectionRule") = collectionRule
    ' Execute the AddMembershipRule method.
    Set outParams = collection.ExecMethod_("AddMembershipRule", inParam) 
    If Err <> 0 Then
        Log ("Failed to add " & machineName & "to the Collection " & collectionID & ". (" & Err.number & ")")
        AddMachineToCollection = Err
        LogExtendedError ()
        Exit Function
    End If
    On Error Goto 0
      
    ' Return success.
    Log ("Successfully added '" & machineName & "' to collection " & collectionID & ".")
    AddMachineToCollection = 0
End Function
 
 
' Gets the MAC Address of the active NIC from WMI.
Function GetMACAddress
    ' Connect to the root\cimv2 namespace and execute a WMI query.
    Dim cimv2Namespace, enabledNICs
    Set cimv2Namespace = GetObject ("winmgmts:{impersonationLevel=impersonate," & "authenticationLevel=pktPrivacy}!\\.\root\cimv2")
    Set enabledNICs = cimv2Namespace.ExecQuery ("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
    If Err <> 0 Then
        Log ("Failed to get the enabled NICs on the machine.(" & Err.number & ")")
        GetMACAddress = Err
        LogExtendedError ()
        Exit Function
    End If
    
    ' Read the MAC address on the last enabled NIC.
    Dim item, mac
    For Each item in enabledNICs
        mac = item.MACAddress
        Log ("Found MAC Address of active NIC: " & mac)
    Next
    
    GetMACAddress = mac
End Function
 
' Gets the machine's SMBIOS GUID.
Function GetSMBIOSGuid
    ' Connect to the root\cimv2 namespace and execute a WMI query.
    Dim cimv2Namespace, results
    Set cimv2Namespace = GetObject ("winmgmts:{impersonationLevel=impersonate," & "authenticationLevel=pktPrivacy}!\\.\root\cimv2")    
    Set results = cimv2Namespace.ExecQuery ("SELECT UUID FROM Win32_ComputerSystemProduct")
       
    ' Process the results of the query.
    Dim record, smbiosGUID
    For Each record in results    
        smbiosGUID = record.UUID
        Log ("Found SMBIOS GUID: " & smbiosGUID)
        ' Filter out bad SMBIOS Guids.
        If smbiosGUID = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF" Or _
           smbiosGUID = "00000000-0000-0000-0000-000000000000" Then
            smbiosGUID = ""
        End If
    Next
    
    ' Return Result.
     GetSMBIOSGuid = smbiosGUID
End Function
 
' Function to validate if the machine with the given resource ID is part of the given collection.
Function VerifyCollectionForResource(collectionID, resourceID)
    Dim iterationNumber : iterationNumber = 0
    Dim isResourcePartOfCollection : isResourcePartOfCollection = False
   
    ' Be in a loop until the resource is not part of the collection and iterationNumber < 30         
    ' Setting the maximum iterations to 30, i.e. setting the maximum time to 30*10 seconds, 5 minutes.
    ' Tune this iteration number based on your site size.
    Do While isResourcePartOfCollection = False And iterationNumber < 30
        Dim wqlQuery, wqlResult
 
        On Error Resume Next 
        
        ' Form the WQL query to verify if the resource is part of the collection.   
        wqlQuery = "select * from SMS_FullCollectionMembership where CollectionID='" & collectionID & "' AND ResourceID='" & resourceID & "'" 
        
        ' Execute the query and verify the number of records in the resultset.
        Set wqlResult = smsSiteNamespace.ExecQuery (wqlQuery)
 
        If wqlResult.Count = 0 Then
            ' No records in the resultset. The machine is not part of the collection yet.
            Log ("Waiting for system with ResourceID: " & resourceID &_
                 " to show up in Collection: " & collectionID & ". (Error = " & Err.number & ")")
            isResourcePartOfCollection = False
            
            ' Sleep for 10 seconds before rechecking
            Sleep (10 * 1000)
        Else
            Log ("Found Machine with ResourceID " & resourceID & " in Collection " & collectionID)
            isResourcePartOfCollection = True
        End If  
        
        On Error Goto 0                
        
        ' Increase the iteration count
        iterationNumber = iterationNumber + 1
    Loop
    
    If (isResourcePartOfCollection = True) Then
        ' Resource is part of the collection. Return 0.
        VerifyCollectionForResource = 0
    Else
        ' Resource is still not part of the collection. Return 1.
        VerifyCollectionForResource = 1
    End If
    
End Function
 
' Subroutine to simulate Sleep in .HTA
Sub Sleep(milliSecs)
    CONST HIDEWINDOW = 0
    CONST WAITFORCOMPLETION = TRUE
    Dim cmdToPing
 
    ' Because HTA doesn't use Windows Script Host, it uses IE Script Host we
    ' can't use WScript.Sleep
    ' Workaround: send one ping command to fake address with a wait for reply
    ' value set in milliseconds
    cmdToPing = "cmd /c ping 1.1.1.1 -n 1 -w " & milliSecs
    With CreateObject("WScript.Shell")
        .Run cmdToPing, HIDEWINDOW, WAITFORCOMPLETION
    End With
End Sub
 
' This function logs the additional error information from the WMI and SMS error objects.
Function LogExtendedError
    On Error Resume Next
    
    Dim extendedStatus
    Set extendedStatus = CreateObject ("WbemScripting.SWBEMLastError")
     
    ' Determine the type of error.
    If extendedStatus.Path_.Class = "__ExtendedStatus" Then
        Log ("WMI Error: " & extendedStatus.Description)
    ElseIf extendedStatus.Path_.Class = "SMS_ExtendedStatus" Then
        Log ("SMS Provider Error")
        Log ("Description: " & extendedStatus.Description)
        Log ("Error Code:  " & extendedStatus.ErrorCode)
    End If
    
    On Error Goto 0
End Function 
 
' Functions to read the UI.
 
' **************************************************************************
' **************************************************************************
          'msgbox "Variables1.0" & VBCrlf & "FullComputerName: " & FullComputerName & VBCrlf & "MachineType: " & MachineType & VBCrlf & "BarcodeID: " & BarcodeID
          'SET env = CreateObject("Microsoft.SMS.TSEnvironment")
          'get the machine type from the Task Sequence to determin "Laptop, Desktop, or VMware" prefix
          'machinetype = env("NCL-HIS_OSDMachineType")
          'msgbox "Variables1.1" & VBCrlf & "FullComputerName: " & FullComputerName & VBCrlf & "MachineType: " & MachineType & VBCrlf & "BarcodeID: " & BarcodeID	
 
 sub DoBarcodeProcess
	' Get the barcode as scanned from the user and set as "BarcodeID"
	  BarcodeID = BarcodeInputFromUser.value
	  SET env = CreateObject("Microsoft.SMS.TSEnvironment")
          msgbox "Variables1.2" & VBCrlf & "FullComputerName: " & FullComputerName & VBCrlf & "MachineType: " & MachineType & VBCrlf & "BarcodeID: " & BarcodeID	
	  machinetype = env("NCL-HIS_OSDMachineType")
 
	  env("OSDComputerName") = MachineType & "-" & BarcodeID
 
 
          'now update the elements displayed to the user
	  document.getElementById("NCL-HIS_OSDMachineType").innerHTML="NCL-HIS_OSDMachineType: " & machinetype
	  document.getElementById("BarcodeID").innerHTML="BarcodeID: " & BarcodeID
	  document.getElementById("OSDComputerName").innerHTML="OSDComputerName: " & env("OSDComputerName")
	  ClearTextBoxes
	  BarcodeInputFromUser.focus
          msgbox "Variables2" & VBCrlf & "FullComputerName: " & FullComputerName & VBCrlf & "MachineType: " & MachineType & VBCrlf & "BarcodeID: " & BarcodeID
 end sub
 
 
 Sub WaitingForEnterKey   'This function waits for ENTER key from barcode reader or keyoard
                          'when ENTER key is received, the function "DoProcess" is called
      If Window.Event.KeyCode = 13 Then
      DoBarcodeProcess
      End If
 End Sub
 
 
  
 Sub ClearTextBoxes    'clear text boxes after the barcode is scanned so it can be scanned again if required
    	  BarcodeInputFromUser.Value = "" 
 End Sub
 
' **************************************************************************
' **************************************************************************
 
 
' Get the entered computer name.
Function GetComputerName 
    Log ("Entered Computer Name: " & txtComputerName.value )
    GetComputerName = txtComputerName.value
End Function
 
' Get the entered Provider Account.
Function GetProviderAccount 
    Log ("Entered Provider Account: " & txtProviderAccount.value )
    GetProviderAccount = txtProviderAccount.value
End Function
 
' Get the entered Provider Account's Password.
Function GetProviderPassword 
    GetProviderPassword = txtProviderPassword.value
End Function
 
</script>
</head>
<Body>
<body onkeypress='vbs:WaitingForEnterKey'>
<table width="895" border="0">
<tr>
                <td width="270">NCL-HIS System Build Process</td>
                <td width="233">&nbsp;</td>
                <td width="334">&nbsp;</td>
              </tr>
              <tr>
                <td colspan="2">Add Workstation to SCCM Collection</td>
                <td>&nbsp;</td>
              </tr>
            </table>
<table width="897" border="0">
  <tr>
    <td width="287"><div align="right">User Name:</div></td>
    <td colspan="2"><input type="text" maxlength="256" id="txtProviderAccount" style="width: 328px" value=""></td>
  </tr>
  <tr>
    <td><div align="right">Password:</div></td>
    <td colspan="2"><input type="password" maxlength="256" id="txtProviderPassword" style="width: 327px" value=""></td>
  </tr>
  <tr>
    <td><div align="right">BarcodeID:</div></td>
    <td colspan="2"><input type=text id="BarcodeInputFromUser" name=BarcodeInputFromUser size=10</td>
  </tr>
  <tr>
    <td><div align="right">Computer name to be given to this machine:</div></td>
    <td colspan="2"><input type="text" maxlength="256" id="txtComputerName" style="width: 327px" value=""></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td width="191"><input id=runButton  class="button" type="button" value="Add Machine Now" name="run_button"  onClick="Main"></td>
    <td width="405"><input id=DoBarcodeProcess  class="button" type="button" value="DoBarcodeProcess" name="DoBarcodeProcess"  onClick="DoBarcodeProcess"></td>
  </tr>
</table>
	<br><textarea  title="Logs" id="logTextArea" rows="10" style="width:100%" readonly="readOnly" ></textarea>
 
  <form>
     <input type="hidden" id="Process" onClick="self.DoBarcodeProcess()" value="Process" enabled=no>
  </form>
 
<div id="NCL-HIS_OSDMachineType"> NCL-HIS_OSDMachineType </div>
<div id="BarcodeID"> BarcodeID </div>
<div id="OSDComputerName"> OSDComputerName </div>
</Body>
</html>

Open in new window

0
Comment
Question by:alliedfusion
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 

Accepted Solution

by:
alliedfusion earned 0 total points
ID: 24313828
Resolved

I have no idea why this is the case, but the variables declaration section needed "Dim Env"

This is unusual as the code works fine when run as the SCCM "system account user" without declaring the "Env" variable.  However, it appears that variable "Env" must be declared when the code is run as a Domain User.

Code now works ok

resolultion in the code snippet below
' Global Variables.
' Logging related variables.
Dim isLogHidden : isLogHidden = False
Dim logFileSystemObject : logFileSystemObject = Null
' Command line arguments.
Dim providerName, provSiteCode, collectionIDToAddTo
' SMS Provider namespace objects.
Dim smsSiteNamespace : smsSiteNamespace = Null
Dim isSMSSiteNamespaceSet : isSMSSiteNamespaceSet = False
Dim machineMACAddress, machineSMBIOSGuid
Dim Env

Open in new window

0
 
LVL 1

Expert Comment

by:LoboMax
ID: 24914451
always declare your variables!
this usually happens when you are passing values to another function or routine.
if not declared it will not pass any values.
0

Featured Post

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Over the years I have built up my own little library of code snippets that I refer to when programming or writing a script.  Many of these have come from the web or adaptations from snippets I find on the Web.  Periodically I add to them when I come…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question