Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Convert vbs code into a standard template

$
0
0

Appreciate if anyone can guide/show me on how to convert or copy the original vbs code into a standard template. I have tried copy and paste all the code into Sub Main but been getting errors. FYI, i have taken out all the function section and placed it outside Sub Main but still getting error. Appreciate some help here. Thanks in advance.

 Original VBS code
 
' -------------------------------------------------------------------------------- 
' Usage 
' -------------------------------------------------------------------------------- 
 
Sub ShowUsage 
   Wscript.Echo "- USAGE: WSCRIPT GetTPM-OwnerInfo.vbs [Computername]" & VbCrLf & VbCrLf & "- Must run from privileged DOS prompt (for example HPCS or DO ID)" & VbCrLf & VbCrLf & "- If no computer name is specified, then the local computer is assumed." & VbCrLf & VbCrLf & "- Runs from local domain only cannot search items from another domain." & VbCrLf & VbCrLf & "- option during script to export to a file which will be saved in the same folder as this file executed."
WScript.Quit 
End Sub 

' -------------------------------------------------------------------------------- 
' Parse Arguments 
' -------------------------------------------------------------------------------- 
 
Set args = WScript.Arguments 
 
Select Case args.Count 
   
  Case 0 
      ' Get the name of the local computer       
      Set objNetwork = CreateObject("WScript.Network") 
      strComputerName = objNetwork.ComputerName 
     
  Case 1 
    If args(0) = "/?" Or args(0) = "-?" Then 
      ShowUsage 
    Else 
      strComputerName = args(0) 
    End If 
   
  Case Else 
    ShowUsage 
 
End Select 

' -------------------------------------------------------------------------------- 
' Get path to Active Directory computer object associated with the computer name 
' -------------------------------------------------------------------------------- 
 
Function GetStrPathToComputer(strComputerName)  
 
    ' Uses the global catalog to find the computer in the forest 
    ' Search also includes deleted computers in the tombstone 
 
    Set objRootLDAP = GetObject("LDAP://rootDSE") 
    namingContext = objRootLDAP.Get("defaultNamingContext") ' e.g. string dc=xom.com,dc=com     
 
    strBase = "<GC://" & namingContext & ">" 
  
    Set objConnection = CreateObject("ADODB.Connection")  
    Set objCommand = CreateObject("ADODB.Command")  
    objConnection.Provider = "ADsDSOOBject"  
    objConnection.Open "Active Directory Provider"  
    Set objCommand.ActiveConnection = objConnection  
 
    strFilter = "(&(objectCategory=Computer)(cn=" &  strComputerName & "))" 
    strQuery = strBase & ";" & strFilter  & ";distinguishedName;subtree"  
 
    objCommand.CommandText = strQuery  
    objCommand.Properties("Page Size") = 100  
    objCommand.Properties("Timeout") = 100 
    objCommand.Properties("Cache Results") = False  
 
    ' Enumerate all objects found.  
 
    Set objRecordSet = objCommand.Execute  
    If objRecordSet.EOF Then 
      WScript.echo "The computer name '" &  strComputerName & "' cannot be found." 
      WScript.Quit 1 
    End If 
 
    ' Found object matching name 
 
    Do Until objRecordSet.EOF  
      dnFound = objRecordSet.Fields("distinguishedName") 
      GetStrPathToComputer = "LDAP://" & dnFound 
      objRecordSet.MoveNext  
    Loop  
 
 
    ' Clean up.  
    Set objConnection = Nothing  
    Set objCommand = Nothing  
    Set objRecordSet = Nothing  
 
End Function 

' -------------------------------------------------------------------------------- 
' Securely access the Active Directory computer object using Kerberos 
' -------------------------------------------------------------------------------- 
 
Set objDSO = GetObject("LDAP:") 
strPath = GetStrPathToComputer(strComputerName) 
 
 
Msgbox "Object Found at location: " + strPath, 64, "Get TPM Owner Hash from AD"
 
Const ADS_SECURE_AUTHENTICATION = 1 
Const ADS_USE_SEALING = 64 '0x40 
Const ADS_USE_SIGNING = 128 '0x80 
 
Set objComputer = objDSO.OpenDSObject(strPath, vbNullString, vbNullString, _ 
                                   ADS_SECURE_AUTHENTICATION + ADS_USE_SEALING + ADS_USE_SIGNING) 
 
' -------------------------------------------------------------------------------- 
' Get the TPM owner information from the Active Directory computer object 
' -------------------------------------------------------------------------------- 
 
Dim OutPutToFile 

strOwnerInformation = objComputer.Get("msTPM-OwnerInformation") 

OutPutToFile = Msgbox("TPM Owner Information: " & strOwnerInformation & VbCrLf & VbCrLf & "Do you wish to save this as a TPM Owner file?", VbYesNo, "Get TPM Owner Hash from AD")

If OutPutToFile = VbYes then

Dim ObjFso 
Dim ObjFile

Set ObjFso = CreateObject("Scripting.FileSystemObject")

Set ObjFile = ObjFso.CreateTextFile(StrComputername & ".tpm")

ObjFile.WriteLine("<?xml version=" & Chr(34) & "1.0" & Chr(34) & " encoding=" & Chr(34) & "UTF-8" & Chr(34) & "?>")
ObjFile.WriteBlankLInes(1) 
ObjFile.WriteLine("<ownerAuth>" & StrOwnerInformation & "</ownerAuth>") 

ObjFile.Close

Wscript.quit

Else 
' MsgBox "Answer was No save as file"
wscript.quit

End If

-----------------------------------------------------------------------------------------------

VBS Template

Option Explicit

.
'// -------------------------------------------------------------------------------------------- 

'// --------------------------------------------------------------------------------------------
'// Variable Declarations
'// --------------------------------------------------------------------------------------------
'// *****  Change Logging Path and File Name Here  *****
Dim sLogContext: sLogContext = "User" '// or "System" '// or 
Dim sLogFolder: sLogFolder = "Template" '// Folder Name
Dim sOutFileName: sOutFileName = "Template.log" '// Log File Name
'// ****************************************************
Const HKCR = &H80000000
Const HKCU = &H80000001
Const HKLM = &H80000002
Const HKU  = &H80000003
Const HKCC = &H80000005
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oWNet: Set oWNet = CreateObject("WScript.Network")
Dim oShell: Set oShell = CreateObject("WScript.Shell")
Dim oReg: Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
Dim sScriptPath: sScriptPath = Left(WScript.ScriptFullName,Instr(WScript.ScriptFullName,WScript.ScriptName)-2)
Dim sOSBit: sOSBit = CStr(GetObject("winmgmts:root\cimv2:Win32_Processor='cpu0'").AddressWidth) '// Will be 32 or 64
Dim bIs64bit: bIs64bit = sOSBit = "64"
Dim bIsVM: bIsVM = IsVirtualMachine()
Dim sLogRoot: sLogRoot = "C:\XOM\Logs"
Dim sOutFilePath: sOutFilePath = oFSO.BuildPath(oFSO.BuildPath(sLogRoot,sLogContext),sLogFolder) '// Looks like "C:\XOM\Logs\User\Template"
Dim iExitCode: iExitCode = 0
Dim sUserName: sUserName = oWNet.UserName
Dim sUserDomain: sUserDomain = oWNet.UserDomain
Dim sMachineName: sMachineName = oWNet.ComputerName
Dim sCMDArgs: sCMDArgs = GetArgs()
Dim bDebug: bDebug = (InStr(LCase(sCMDArgs),"/debug") > 0) Or (InStr(LCase(sCMDArgs),"-debug") > 0)
Dim sNoRelaunchArg: sNoRelaunchArg = "/norelaunch"
Dim sSysNative: sSysNative = oFSO.BuildPath(oShell.ExpandEnvironmentStrings("%WINDIR%"), "Sysnative")
Dim bAllow64bitRelaunch : bAllow64bitRelaunch = True
Dim oLogFile
Dim bLogFileOpen
'// Script Specific Variables



'// --------------------------------------------------------------------------------------------
'// Main Body
'// --------------------------------------------------------------------------------------------

'// Turn off On Error Resume Next if in Debug Mode
If bDebug Then On Error GoTo 0

'// Prior to logging, determine if we are in the 32-bit scripting host on a 64-bit machine and need and want to re-launch
If (InStr(LCase(sCMDArgs),LCase(sNoRelaunchArg)) = 0) And bIs64bit And oFSO.FolderExists(sSysNative) And bAllow64bitRelaunch Then
RelaunchIn64 '// Relaunch as a 64bit process
Else
RunScript '// Run the script
End If

'// Quiting with our exit code
WScript.Quit iExitCode

'// --------------------------------------------------------------------------------------------
'// Subroutines and Functions
'// --------------------------------------------------------------------------------------------

'// --------------------------------------------------------------------------------------------
'// Sub: Main
'// Purpose: To initiate the main script
'// Variables: None
'// --------------------------------------------------------------------------------------------
Sub Main()

'// Logging Global Variables
'// Add all global variables below that pertain to the function of the script for
'//troubleshooting
LogIt "", 0
LogIt "Variables:", 0
LogIt "Script Title = " & SCRIPT_TITLE, 1
LogIt "Script Name = " & WScript.ScriptName, 1
LogIt "Script Version = " & SCRIPT_VERSION, 1
LogIt "Script Path = " & sScriptPath, 1
LogIt "User Name = " & sUserDomain & "\" & sUserName, 1
LogIt "Machine Name = " & sMachineName, 1
LogIt "OS Architecture = " & sOSBit & "-bit", 1
LogIt "Is 64-bit OS = " & bIs64bit, 1
LogIt "Is Virtual Machine = " & bIsVM, 1
LogIt "Log File = " & oFSO.BuildPath(sOutFilePath,sOutFileName), 1
LogIt "Command Line Arguments = " & sCMDArgs, 1
LogIt "Debug = " & bDebug, 1



'// Clear any errors before exiting Main.
Err.Clear

End Sub

'// --------------------------------------------------------------------------------------------
'// Sub Name: RelaunchIn64
'// Purpose: To relaunch the script as a 64bit process
'// Variables: None
'// --------------------------------------------------------------------------------------------
Sub RelaunchIn64

'// Make sure we continue on if there is error, but only in this sub, unless in Debug Mode
If Not bDebug Then On Error Resume Next

'// We need to relaunch
Dim sEngine : sEngine = Split(WScript.FullName,"\")(UBound(Split(WScript.FullName,"\")))
Dim oResult : Set oResult = oShell.Exec(oFSO.BuildPath(sSysNative,sEngine) & " """ & WScript.ScriptFullName & """ " & sCMDArgs & " " & sNoRelaunchArg)

'// Loop until the script is done so that we can return the exit code to SCCM or whoever launched us
Do While oResult.Status = 0
  WScript.Sleep 500
Loop
iExitCode = oResult.ExitCode

End Sub

'// --------------------------------------------------------------------------------------------
'// Sub Name: RunScript
'// Purpose: Run the normal process of the script, regardless of relaunch
'// Variables: None
'// --------------------------------------------------------------------------------------------
Sub RunScript

'// Make sure we continue on if there is error, but only in this sub, unless in Debug Mode
If Not bDebug Then On Error Resume Next

'// Starting the logging
StartLog

'// Calling Main Sub
Main()

'// Make sure that we made it all the way through and didn't throw an unhandled error
If (err.number <> 0) and (iExitCode = 0) Then 
iExitCode = 9999
LogIt "Unhandled Exception Thrown!",0
LogIt "Error: " & Err.Number,1
LogIt "Message: " & Err.Description,1
End If

'// Stopping the logging
StopLog

End Sub

'// --------------------------------------------------------------------------------------------
'// Sub Name: StartLog
'// Purpose: To try to open and start the log file
'// Variables: None
'// --------------------------------------------------------------------------------------------
Sub StartLog

'// We have to have this to make sure we catch the error and don't display it.
On Error Resume Next

'// Declaring and Setting Variables
Dim sAddLines

'// Creating the OutFilePath if it does not exist
CreatePath(sOutFilePath)

'// Making sure that the log file is not too large
sAddLines = ""
If CheckFile(oFSO.BuildPath(sOutFilePath,sOutFileName),1048576) Then
sAddLines = "Previous Log File Cleared On " & Now
End If

'// Opening the output file
Err.Clear
Set oLogFile = oFSO.OpenTextFile(oFSO.BuildPath(sOutFilePath,sOutFileName),8,True)

If Err.Number = 0 Then

'// Returning that the file was opened
bLogFileOpen = True

Else

'// Stating that the file was not opened
bLogFileOpen = False
ShowDebug "Log file could not be opened!" & vbNewLine & vbNewLine & "Continuing Script with no logging."

End If

'// Continuing to call LogIt because we may have Debug On

'// Setting the time and date of the logging
LogIt sAddLines, 0
LogIt "================================================================================================", 0
LogIt SCRIPT_TITLE & " (" & WScript.ScriptName & ") " & SCRIPT_VERSION, 0
LogIt "================================================================================================", 0
LogIt "Script Started at " & Now, 0

'// Clear any errors so that they don't register later
Err.Clear

End Sub

'// --------------------------------------------------------------------------------------------
'// Sub Name: StopLog
'// Purpose: To stop and close the log file
'// Variables: None
'// --------------------------------------------------------------------------------------------
Sub StopLog

'// Logging when we finished
LogIt "", 0
LogIt "Script Completed at " & Now & " with Exit Code " & iExitCode, 0
LogIt "================================================================================================", 0
LogIt "================================================================================================", 0

'// Checking to see if the log file is open
If bLogFileOpen Then

'// Closing the log file
oLogFile.Close

End If

End Sub

'// --------------------------------------------------------------------------------------------
'// Sub Name: ShowDebug
'// Purpose: To display passed text to the user if the variable Debug is Set
'//to True
'// Variables: Info
'//Info - Holds text to be displayed
'// --------------------------------------------------------------------------------------------
Sub ShowDebug(Info)

'// Displaying the info passed if debug is set to True
If bDebug Then
WScript.Echo Info
End If

End Sub

'// --------------------------------------------------------------------------------------------
'// Sub Name: LogIt
'// Purpose: To write the passed text to the output file
'// Variables: Info, NumberOfTabs
'//Info - Holds text to be displayed
'//NumberOfTabs - The number of tabs to indent the Info
'// --------------------------------------------------------------------------------------------
Sub LogIt(Info, NumberOfTabs)

'// Declaring and Setting Variables
Dim iCount
Dim stInfo : stInfo = Info

'// Make sure we didn't get a bad number of tabs
If NumberOfTabs > 0 Then

'// Adding the tabs
For iCount = 1 To NumberOfTabs
'stInfo = vbTab & stInfo
stInfo = "    " & stInfo
Next

End If

'// Checking to see if the log file is open
If bLogFileOpen Then

'// Writing the info to the log file
oLogFile.WriteLine(stInfo)

End If

'// Displaying the info passed if debug is set to True
ShowDebug(stInfo)

End Sub

'// --------------------------------------------------------------------------------------------
'// Sub Name: CreatePath
'// Purpose: To create the folder path of the given path if it doesn't exist.
'// Variables: sPath
'//sPath - The path to be created
'// --------------------------------------------------------------------------------------------
Sub CreatePath(sPath)

'// Setting On Error Resume Next for the UNC folders
On Error Resume Next

'// Declaring and Setting Variables
Dim sFolders : sFolders = Split(sPath,"\")
Dim iCount
Dim iCount2
Dim sFolder
Dim bIsUNC : bIsUNC = False

'// Checking to see if this is UNC
If Left(sPath,2) = "\\" Then
bIsUNC = True
End If

'// Building the structure one folder at a Time
For iCount = LBound(sFolders) To UBound(sFolders)

'// Adding our \\ for UNC paths
If bIsUNC Then
sFolder = "\\"
Else
'// Resetting the current full path
sFolder = ""
End If

'// Putting the current folder on to the full path
For iCount2 = LBound(sFolders) To iCount

'\\ Making sure that this is not an empty string
If sFolders(iCount2) <> "" Then
sFolder = sFolder & sFolders(iCount2) & "\"
End If

Next

'// Make sure that we actually have something to look at
If Len(sFolder) > 2 Then

'// Checking to see if the folder exists, creating if it doesn't
If Not oFSO.FolderExists(sFolder) Then
oFSO.CreateFolder(sFolder)
End If

End If

Next

End Sub

'// --------------------------------------------------------------------------------------------
'// Function Name: CheckFile
'// Purpose: To clear the given file if it exceeds the given size.
'// Variables: sFilePath, lFileSize
'//sFilePath - The full path to the file to be created
'//lFileSize - The maximum file size in bytes (1048576 = 1 Mb)
'//Returns: Boolean value if the file was cleared or not
'// --------------------------------------------------------------------------------------------
Function CheckFile(sFilePath,lFileSize)

'// Setting the default return
CheckFile = False

'// Make sure that the file exists
If oFSO.FileExists(sFilePath) Then

'// Making the comparison
If oFSO.GetFile(sFilePath).Size > lFileSize Then

'// Clear the file
Set oLogFile = oFSO.OpenTextFile(sFilePath,2,True)
oLogFile.Close()

'// Returning that the file was cleared
CheckFile = True

End If

End If

End Function

'// --------------------------------------------------------------------------------------------
'// Function Name: GetArgs
'// Purpose: To create a single string with all of the command line arguments passed to the script.
'// Variables: None
'//Returns: String value containing all command line arguments, space delimited
'// --------------------------------------------------------------------------------------------
Function GetArgs()

'// Declaring and Setting Variables
Dim sReturn : sReturn = ""
Dim oItem

'// Loop through all of the arguments
For Each oItem in WScript.Arguments

'// Add the argument to the return string
sReturn = sReturn & oItem & " "

Next

'// Return our string
GetArgs = sReturn

End Function

'// --------------------------------------------------------------------------------------------
'// Function Name: IsVirtualMachine
'// Purpose: To identify if the machine is a virtual machine or not
'// Variables: None
'//Returns: Boolean value (True or False) of whether the machine is a virtual machine or not
'// --------------------------------------------------------------------------------------------
Function IsVirtualMachine

'// Declaring and Setting Variables
Dim oWMI : Set oWMI = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
Dim cSystem : Set cSystem = oWMI.ExecQuery ("Select * from Win32_ComputerSystem")
Dim bReturn : bReturn = False
Dim oItem
Dim sModel

'// Loop through all entries in the System class
For Each oItem In cSystem

'// Check to see if we found the VM chassis flag
sModel = Trim(LCase(oItem.Model))
If (sModel = "virtual machine") Or (sModel = "vmware virtual platform") Then bReturn = True

Next 

'// Return our value
IsVirtualMachine = bReturn

End Function


Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>