Jump to content

Need help debugging /fixing this mission critical script


Recommended Posts

Hi

I have to push out a software called verdiem that controls power management to over 1000 pc's based on the os.

If it is xp 32 bit /windows 7 32 bit then install the 32 bit client,

if it is windows 7 64 bit then install the 64 bit client.

if the service already is present to nothing,

I been able to piece meal together scripts I found from the internet to detect the os, and the service, but I can't get the program to run from a shared drive using osshell.run command. I'd really appreciate some help this is really urgent and I have been stuck for 3 days.

''''''''''''''''''''''''''''''''''''''
'
' Variable Declaration
'
''''''''''''''''''''''''''''''''''''''

Dim myOS, myArch, myServiceName, myServiceDisplayName, myRunningState, myStatus, myExec
Dim strComputer, oWMIService, colOSInfo, oOSProperty, strOSFamily

strComputer = "."


''''''''''''''''''''''''''''''''''''''
'
' OS Name
'
''''''''''''''''''''''''''''''''''''''

Set oWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colOSInfo = oWMIService.ExecQuery("Select * from Win32_OperatingSystem")


For Each oOSProperty in colOSInfo
strCaption = oOSProperty.Caption
Next

myOS = strCaption


''''''''''''''''''''''''''''''''''''''
'
' Architechture Type - 32 vs 64 bit
'
''''''''''''''''''''''''''''''''''''''

Set WshShell = CreateObject("WScript.Shell")

OsType = WshShell.RegRead("HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE")

If OsType = "x86" then
myArch = 32

elseif OsType = "AMD64" then
myArch = 64
end if


''''''''''''
' SERVICES
'
''''''''''''

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20

arrComputers = Array("localhost")

For Each strComputer In arrComputers

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Service", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)

For Each objItem In colItems

If objItem.DisplayName = "Verdiem Surveyor Client" Then

myServiceName = objItem.Name
myServiceDisplayName = objItem.DisplayName
myRunningState = objItem.State
myStatus = objItem.Status

If myRunningState <> "Running" Then

Return = objItem.StartService()

If Return = 0 Then
WScript.Echo "Service started"
Else
WScript.Echo "Service could not be started. Return = " & Return
myRunningState = "Not Running"
End If
End if

End if

Next

Next

''''''''''''''''''''''''''''''''''''''
'
' Debug print
'
''''''''''''''''''''''''''''''''''''''

WScript.Echo "OS: " & myOS
WScript.Echo "Arch: " & myArch
WScript.Echo "Service Name: " & myServiceName
WScript.Echo "Service Display Name: " & myServiceDisplayName
WScript.Echo "Running State: " & myRunningState
WScript.Echo "Status: " & myStatus


''''''''''''''''''''''''''''''''''''''
'
' Install Logic
'
''''''''''''''''''''''''''''''''''''''

Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")


If myServiceDisplayName <> "Verdiem Surveyor Client" Then

If myRunningState <> "Running" Then

If myOS = "XP" Then
Wscript.Echo "Execing Client32 on XP"

oShell.run "msiexec.exe /i" "Z:\VerdiemSurveyor\Clientx86\Verdiem Surveyor Client.msi /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

End if

If myOS = "Microsoft Windows 7 Professional" Then

If myArch = 32 Then
WScript.Echo "Execing Client32 on 7"

oShell.run "msiexec.exe /i" "Z:\VerdiemSurveyor\Clientx86\Verdiem Surveyor Client.msi /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

End if

if myArch = 64 Then
WScript.Echo "Execing Client64 on 7"

oShell.run "msiexec.exe /i" "Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

End if
End if
Else
WScript.Echo "Install condidtions not met... Aborting"
End if
End if

Set oShell = Nothing

Edited by clivebuckwheat
Link to comment
Share on other sites


Just by looking (haven't actually tried any of it), this seems to be the culprit:

oShell.run "msiexec.exe /i" "Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

There are spaces in the MSI's file name so you'd have to wrap that around with quotes, and you'd want a space after /i too, and you can't just end a string with " add a space and continue by adding another " (if that actually was your intent) -- you'd have to add a & between both for that to work. This fails parsing, and if you added the ampersand to have

oShell.run "msiexec.exe /i" & "Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

then it would pass these as arguments to msiexec.exe:

1st arg: /iZ:\VerdiemSurveyor\Clientx64\Verdiem

2nd arg: Surveyor

3rd arg: Client.msi

4th arg: /qb

5th arg: SERVER_NAME=myservername.ca

6th arg: SERVER_PORT=5600

which is not what you want. I would try this:

oShell.run "msiexec.exe /i ""Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi"" /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

which passes these arguments:

1st arg: /i

2nd arg: Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi

3rd arg: /qb

4th arg: SERVER_NAME=myservername.ca

5th arg: SERVER_PORT=5600

That should work.

Link to comment
Share on other sites

Just by looking (haven't actually tried any of it), this seems to be the culprit:

oShell.run "msiexec.exe /i" "Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

There are spaces in the MSI's file name so you'd have to wrap that around with quotes, and you'd want a space after /i too, and you can't just end a string with " add a space and continue by adding another " (if that actually was your intent) -- you'd have to add a & between both for that to work. This fails parsing, and if you added the ampersand to have

oShell.run "msiexec.exe /i" & "Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

then it would pass these as arguments to msiexec.exe:

1st arg: /iZ:\VerdiemSurveyor\Clientx64\Verdiem

2nd arg: Surveyor

3rd arg: Client.msi

4th arg: /qb

5th arg: SERVER_NAME=myservername.ca

6th arg: SERVER_PORT=5600

which is not what you want. I would try this:

oShell.run "msiexec.exe /i ""Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi"" /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

which passes these arguments:

1st arg: /i

2nd arg: Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi

3rd arg: /qb

4th arg: SERVER_NAME=myservername.ca

5th arg: SERVER_PORT=5600

That should work.

Well at least now I have no compile errors anymore but now the installers do not run, but it picks up the OS type architecture type and then nothing.

The installers reside on a map drive

Z:\VerdiemSurveyor\Clientx86\Verdiem Surveyor Client.msi

Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi

Any thoughts as to why the script is not executing the msi's. It is picking up the correct os type and the correct cpu/architecture?

''''''''''''''''''''
''''''''''''''''''
'
' Variable Declaration
'
'''''''''''''''''''''
'''''''''''''''''

Dim myOS, myArch, myServiceName, myServiceDisplayName, myRunningState, myStatus, myExec
Dim strComputer, oWMIService, colOSInfo, oOSProperty, strOSFamily

strComputer = "."


'''''''''''''''''''''
'''''''''''''''''
'
' OS Name
'
'''''''''''''''''''''
'''''''''''''''''

Set oWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colOSInfo = oWMIService.ExecQuery("Select * from Win32_OperatingSystem")


For Each oOSProperty in colOSInfo
strCaption = oOSProperty.Caption
Next

myOS = strCaption


'''''''''''''''''''''
'''''''''''''''''
'
' Architechture Type - 32 vs 64 bit
'
'''''''''''''''''''''
'''''''''''''''''

Set WshShell = CreateObject("WScript.Shell")

OsType = WshShell.RegRead("HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE")

If OsType = "x86" then
myArch = 32

elseif OsType = "AMD64" then
myArch = 64
end if


''''''''''''
' SERVICES
'
''''''''''''

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20

arrComputers = Array("localhost")

For Each strComputer In arrComputers

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Service", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)

For Each objItem In colItems

If objItem.DisplayName = "Verdiem Surveyor Client" Then

myServiceName = objItem.Name
myServiceDisplayName = objItem.DisplayName
myRunningState = objItem.State
myStatus = objItem.Status

If myRunningState <> "Running" Then

Return = objItem.StartService()

If Return = 0 Then
WScript.Echo "Service started"
Else
WScript.Echo "Service could not be started. Return = " & Return
myRunningState = "Not Running"
End If
End if

End if

Next

Next

'''''''''''''''''''''
'''''''''''''''''
'
' Debug print
'
'''''''''''''''''''''
'''''''''''''''''

WScript.Echo "OS: " & myOS
WScript.Echo "Arch: " & myArch
WScript.Echo "Service Name: " & myServiceName
WScript.Echo "Service Display Name: " & myServiceDisplayName
WScript.Echo "Running State: " & myRunningState
WScript.Echo "Status: " & myStatus


'''''''''''''''''''''
'''''''''''''''''
'
' Install Logic
'
'''''''''''''''''''''
'''''''''''''''''

Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")


If myServiceDisplayName <> "Verdiem Surveyor Client" Then

If myRunningState <> "Running" Then

If myOS = "XP" Then
Wscript.Echo "Execing Client32 on XP"

oShell.run "msiexec.exe /i ""Z:\VerdiemSurveyor\Clientx86\Verdiem Surveyor Client.msi"" /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"
End if

If myOS = "Microsoft Windows 7 Professional" Then

If myArch = 32 Then
WScript.Echo "Executing Client32 on 7"

oShell.run "msiexec.exe /i ""Z:\VerdiemSurveyor\Clientx86\Verdiem Surveyor Client.msi"" /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

End if

if myArch = 64 Then
WScript.Echo "Executing Client64 on 7"

oShell.run "msiexec.exe /i ""Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi"" /qb SERVER_NAME=myservername.ca SERVER_PORT=5600"

End if
End if
Else
WScript.Echo "Install condidtions not met... Aborting"
End if
End if

Set oShell = Nothing


Link to comment
Share on other sites

You need to start adding alerts to your script to help debug - again, I don't know where it would fail (can't run it here, obviously), but that would help. I'll take a deeper look later if I get the chance, because that script seems overly complicated for what you're trying to do, which is simple.

Link to comment
Share on other sites

You need to start adding alerts to your script to help debug - again, I don't know where it would fail (can't run it here, obviously), but that would help. I'll take a deeper look later if I get the chance, because that script seems overly complicated for what you're trying to do, which is simple.

I know it is picking up the right os and architecture type that is why I put the echos in, so I know that 100% works. It is just not running the installers. If I paste the command to run the msi into a run box on an os it works so I know that works. Thanks Cluberti any help would be appreciated, as I am down to the wire on this one.

What I am trying to do is simple yes

1. If os is xp or windows 7 32 bit run the 32 installer

2.if os is windows 7 64 bit run the 64 bit installer

3. if a service called SurveyorSD exists do nothing.

I am learning vb script on the fly so I am not very good yet,

Edited by clivebuckwheat
Link to comment
Share on other sites

OK, I've cleaned up your code and removed the irrelevant bits. I've also made it faster (and easier for you to script against) by adding an updated version of my ScriptHelper class. Here's the updated script - I cannot verify that it will work in your environment 100%, but I did create a dummy .msi and put it on a Z drive (in that path) and it worked fine. Code:

'// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'//
'// NAME: Verdiem_Surveyor_Client_Install.vbs
'//
'// Original: clivebuckwheat @ MSFN Forums
'// Updated: cluberti @ MSFN Forums
'// Last Update: 21st September 2010
'// Version: 2.1
'//
'//
'// Comment: Installs Verdiem Surveyor Client.msi
'//
'// NOTE: Provided as-is - usage of this source assumes that you are at the
'// very least familiar with the vbscript language being used and
'// the tools used to create and debug this file.
'//
'// In other words, if you break it, you get to keep the pieces.
'//
'// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


'// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'//
'// Ensure that cscript is the engine used to run this script, and that we have an admin token

Dim ScriptHelper
Set ScriptHelper = New ScriptHelperClass

ScriptHelper.RunMeWithCscript()
'ScriptHelper.ElevateThisScript()


'// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'//
'// Set variables

CONST wbemFlagReturnImmediately = &h10
CONST wbemFlagForwardOnly = &h20

strComputer = ScriptHelper.Network.ComputerName
Arch = ""

Set colOSItems = ScriptHelper.WMI.ExecQuery( _
"SELECT * FROM Win32_OperatingSystem",,48)

Set colServices = ScriptHelper.WMI.ExecQuery( _
"SELECT * FROM Win32_Service", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)


'//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'//
'// Get OS Architecture from WMI:

For Each objOSItem in colOSItems
If objOSItem.BuildNumber => 6000 Then
'Vista/Win7 - Get 32-bit or 64-bit directly from WMI:
Arch = objOSItem.OSArchitecture
Else
'Not Vista or Win7 - check XP or 2003 the hard way:
If objOSItem.BuildNumber = 2600 Then
'x86 XP - build 2600 is only x86:
Arch = "32-bit"
ElseIf objOSItem.BuildNumber = 3790 Then
'Build 3790 could be x64 XP/2003 or x86 2003 - check further:
If Not ScriptHelper.FileSystem.FolderExists(ScriptHelper.Environment.ProgramFilesX86) Then
'x86 2003
Arch = "32-bit"
Else
'x64 XP/2003
Arch = "64-bit"
End If
End If
End If
Next


'//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'//
'// Check for the existence of the Verdiem Surveyor Client service:

For Each objService In colServices
If objService.DisplayName = "Verdiem Surveyor Client" Then
If objService.State <> "Running" Then
Return = objService.StartService()
If Return <> 0 Then
WScript.Echo "Service installed but could not be started. Result = " & Return
WScript.Echo ""
End if
Else
WScript.Echo "Service installed and running - exiting script"
WScript.Quit
End If
Else
'Service is not installed - continuing new installation
End If
Next


'//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'//
'// Install the x86 or x86-64 version of the client based on Arch:

If Arch = "32-bit" Then
WScript.Echo "Installing the " & Arch & " version of Verdiem Surveyor Client..."
WScript.Echo ""
Set isRunning = ScriptHelper.Shell.Exec("msiexec /i ""Z:\VerdiemSurveyor\Clientx86\Verdiem Surveyor Client.msi"" /qb SERVER_NAME=myservername.ca SERVER_PORT=5600")
Do While isRunning.Status = 0
WScript.Sleep 100
execOutput = isRunning.StdOut.ReadAll
Loop
ElseIf Arch = "64-bit" Then
WScript.Echo "Installing the " & Arch & " version of Verdiem Surveyor Client..."
WScript.Echo ""
Set isRunning = ScriptHelper.Shell.Exec("msiexec /i ""Z:\VerdiemSurveyor\Clientx64\Verdiem Surveyor Client.msi"" /qb SERVER_NAME=myservername.ca SERVER_PORT=5600")
Do While isRunning.Status = 0
WScript.Sleep 100
execOutput = isRunning.StdOut.ReadAll
Loop
Else
WScript.Echo "Well, the script got this far, but still failed. Contact your administrator if you see this message!"
End if


'// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'//
'// ScriptHelperClass and EnvironmentClass are helper classes to simplIfy
'// script work. Declare and use globally throughout the script.
'//
'// Example code:
'// =============
'//
'// Option Explicit
'// Dim ScriptHelper
'// Set ScriptHelper = New ScriptHelperClass
'//
'// ScriptHelper.RunMeWithCScript()
'// ScriptHelper.ElevateThisScript()
'//
'// WScript.StdOut.Write vbCrLf & "User profile : " & ScriptHelper.Environment.UserProfile
'// WScript.StdOut.Write vbCrLf & "Domain : " & ScriptHelper.Network.UserDomain
'// ScriptHelper.CreateFolder "\\SERVER\Share\Folder\With\Path"
'// ScriptHelper.FileSystem.FileExists("C:\command.com")
'// ScriptHelper.Shell.RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ProductOptions\ProductType")
'//
'//
'// All current members:
'// ====================
'//
'// ScriptHelper.FileSystem: "Scripting.FileSystemObject"
'// ScriptHelper.Network: "WScript.Network"
'// ScriptHelper.Shell: "WScript.Shell"
'// ScriptHelper.ShellApp: "Shell.Application"
'// ScriptHelper.WMI: "WbemScripting.SWbemLocator" (root\cimv2)
'// ScriptHelper.Registry: "winmgmts:{impersonationLevel=impersonate}!\\" & strComputerName & "\root\default:StdRegProv"
'//
'// ScriptHelper.ScriptPath: "FileSystem.GetFile(WScript.ScriptFullName).ParentFolder"
'// ScriptHelper.GetTimeStampString Returns a time and date string with leading zeroes
'// ScriptHelper.GetCurrentUserSID: "WMI.ExecQuery("SELECT * FROM Win32_UserAccount WHERE Name = '" & Network.Username & "' AND Domain = '" & Network.UserDomain & "'", , 48)"
'// ScriptHelper.CreateFolder(strFldPath): "FileSystem.CreateFolder(strDestFold)"
'// ScriptHelper.DeleteFolder(strFldPath): "FileSystem.DeleteFolder strFldPath, True"
'// ScriptHelper.DrawProgress: "WScript.StdOut.Write ChrW(8) & "|" (or "/", "-", and "\" - progress bar "spinner")"
'// ScriptHelper.ClearProgress: "WScript.StdOut.Write ChrW(8) & "done." (replaces "spinner" with the text "done.")"
'//
'// ScriptHelper.RunMeWithCscript: Runs script in cscript - If running under WScript, spawns script as a new process under cscript
'// ScriptHelper.ElevateThisScript: Runs script under admin context, causes UAC / Permission prompt If running as non-admin
'// ScriptHelper.PrintMsg(strMessage) Prints strMessage to screen by calling "WScript.StdOut.Write vbCrLf & strMessage"
'//
'// ScriptHelper.Environment.LogonServer: "GetEnvironmentValue("%LOGONSERVER%")"
'// ScriptHelper.Environment.ProgramFiles: "GetEnvironmentValue("%PROGRAMFILES%")"
'// ScriptHelper.Environment.ProgramFilesX86: "GetEnvironmentValue("%PROGRAMFILES(x86)%")"
'// ScriptHelper.Environment.UserProfile: "GetEnvironmentValue("%USERPROFILE%")"
'// ScriptHelper.Environment.AllUsersProfile: "GetEnvironmentValue("%ALLUSERSPROFILE%")"
'// ScriptHelper.Environment.WinDir: "GetEnvironmentValue("%WINDIR%")"
'// ScriptHelper.Environment.TempDir: "GetEnvironmentValue("%TEMP%")"
'// ScriptHelper.Environment.SMSPKDG: "GetEnvironmentValue("%SMSPKGD%")"
'//
'// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Class ScriptHelperClass

Private objEnvironment
Private objFileSystem
Private objNetwork
Private objShell
Private objShellApp
Private objSWBemlocator
Private objWMI
Private objRegistry
Private currentProgress


Public Computer


Public Property Get Environment
If objEnvironment Is Nothing Then
Set objEnvironment = New EnvironmentClass
objEnvironment.Shell = Shell
End If
Set Environment = objEnvironment
End Property


Public Property Get FileSystem
If objFileSystem Is Nothing Then Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set FileSystem = objFileSystem
End Property


Public Property Get Network
If objNetwork Is Nothing Then Set objNetwork = CreateObject("WScript.Network")
Set Network = objNetwork
End Property


Public Property Get Shell
If objShell Is Nothing Then Set objShell = CreateObject("WScript.Shell")
Set Shell = objShell
End Property


Public Property Get ShellApp
If objShellApp Is Nothing Then Set objShellApp = CreateObject("Shell.Application")
Set ShellApp = objShellApp
End Property


Public Property Get WMI
If objWMI Is Nothing Then
On Error Resume Next
Set objSWBemlocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMI = objSWBemlocator.ConnectServer(Computer, "root\CIMV2")
objWMI.Security_.ImpersonationLevel = 3
On Error Goto 0
End If
Set WMI = objWMI
End Property


Public Property Get Registry
If objRegistry Is Nothing Then Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputerName & "\root\default:StdRegProv")
Set Registry = objRegistry
End Property


Private Sub Class_Initialize()
Computer = "."
Set objEnvironment = Nothing
Set objFileSystem = Nothing
Set objNetwork = Nothing
Set objShell = Nothing
Set objShellApp = Nothing
Set objSWBemlocator = Nothing
Set objWMI = Nothing
Set objRegistry = Nothing
currentProgress = 0
End Sub


Private Sub Class_Terminate
Set objRegistry = Nothing
Set objWMI = Nothing
Set objSWBemlocator = Nothing
Set objShell = Nothing
Set objShellApp = Nothing
Set objNetwork = Nothing
Set objFileSystem = Nothing
Set objEnvironment = Nothing
End Sub


Public Property Get ScriptPath()
ScriptPath = FileSystem.GetFile(WScript.ScriptFullName).ParentFolder
End Property


Public Function GetCurrentUserSID()
Dim intCount, colItems, objItem, strSID

Set colItems = WMI.ExecQuery("SELECT * FROM Win32_UserAccount WHERE Name = '" & Network.Username & "' AND Domain = '" & Network.UserDomain & "'", , 48)

intCount = 0
For Each objItem In colItems
strSID = CStr(objItem.SID)
intCount = intCount + 1
Next

If intCount > 0 Then
GetCurrentUserSID = strSID
Else
GetCurrentUserSID = "NOTFOUND"
End If
End Function


Public Sub CreateFolder(strFldPath)
Dim fldArray, x, intStartIndex, blnUNC, strDestFold
strDestFold = ""

If Left(strFldPath, 2) = "\\" Then
blnUNC = True
intStartIndex = 3 'Start at the first folder in UNC path
Else
blnUNC = False
intStartIndex = 0
End If

fldArray = Split(strFldPath, "\") 'Split folders into array

If fldArray(intStartIndex) = "" Then Exit Sub

For x = intStartIndex To UBound(fldArray)

If strDestFold = "" Then
If blnUNC Then
strDestFold = "\\" & fldArray(x -1) & "\" & fldArray(x) 'Prefix UNC with server and share
Else
strDestFold = fldArray(x)
End If
Else
strDestFold = strDestFold & "\" & fldArray(x) 'Append each folder to end of path
End If
If Not FileSystem.FolderExists(strDestFold) Then FileSystem.CreateFolder(strDestFold)
Next
End Sub


Public Sub DeleteFolder(strFldPath)
If FileSystem.FolderExists(strFldPath) Then FileSystem.DeleteFolder strFldPath, True
End Sub


Public Sub DrawProgress()
Select Case currentProgress
Case 0, 4
WScript.StdOut.Write ChrW(8) & "|"
Case 1, 5
WScript.StdOut.Write ChrW(8) & "/"
Case 2, 6
WScript.StdOut.Write ChrW(8) & "-"
Case 3, 7
WScript.StdOut.Write ChrW(8) & "\"
End Select
currentProgress = currentProgress + 1
If currentProgress = 8 Then currentProgress = 0
End Sub

Public Sub ClearProgress()
currentProgress = 0
WScript.StdOut.Write ChrW(8) & "done."
End Sub


Public Sub RunMeWithCScript()
Dim ScriptEngine, engineFolder, Args, arg, scriptName, argString, scriptCommand

ScriptEngine = UCase(Mid(WScript.FullName, InstrRev(WScript.FullName, "\") + 1))
engineFolder = Left(WScript.FullName, InstrRev(WScript.FullName, "\"))
argString = ""

If ScriptEngine = "WSCRIPT.EXE" Then
Dim Shell
Set Shell = CreateObject("WScript.Shell")
Set Args = WScript.Arguments

For Each arg in Args 'loop though argument array as a collection to rebuild argument string
If InStr(arg, " ") > 0 Then arg = """" & arg & """" 'If the argument contains a space wrap it in double quotes
argString = argString & " " & Arg
Next

'Create a persistent command prompt for the cscript output window and call the script with its original arguments
scriptCommand = "cmd.exe /k " & engineFolder & "cscript.exe """ & WScript.ScriptFullName & """" & argString

Shell.Run scriptCommand, , False
WScript.Quit
Else
Exit Sub 'Already Running with Cscript Exit this Subroutine
End If
End Sub


Public Sub ElevateThisScript()
Const HKEY_CLASSES_ROOT = &H80000000
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_USERS = &H80000003
Const KEY_QUERY_VALUE = 1
Const KEY_SET_VALUE = 2

Dim ScriptEngine, engineFolder, argString, arg, Args, scriptCommand, HasRequiredRegAccess
Dim objShellApp
Set objShellApp = CreateObject("Shell.Application")

ScriptEngine = UCase(Mid(WScript.FullName, InstrRev(WScript.FullName, "\") + 1))
engineFolder = Left(WScript.FullName, InstrRev(WScript.FullName, "\"))
argString = ""

Set Args = WScript.Arguments

For Each arg in Args 'loop though argument array as a collection to rebuild argument string
If InStr(arg, " ") > 0 Then arg = """" & arg & """" 'If the argument contains a space wrap it in double quotes
argString = argString & " " & Arg
Next

scriptCommand = engineFolder & ScriptEngine

Dim objReg, bHasAccessRight
Set objReg = GetObject("winmgmts:"_
& "{impersonationLevel=impersonate}!\\" &_
Computer & "\root\default:StdRegProv")

'Check for administrative registry access rights
objReg.CheckAccess HKEY_LOCAL_MACHINE, "System\CurrentControlSet\Control\CrashControl", _
KEY_SET_VALUE, bHasAccessRight

If bHasAccessRight = True Then
HasRequiredRegAccess = True
Exit Sub
Else
HasRequiredRegAccess = False
objShellApp.ShellExecute scriptCommand, " """ & WScript.ScriptFullName & """" & argString, "", "runas"
WScript.Quit
End If
End Sub


Function AddZero(ByRef strInt1)
If (Len(strInt1) < 2) Then
strInt1 = "0" & CStr(strInt1)
End If
AddZero = strInt1
End Function


Function GetTimeStampString()
Dim sMon, sDay, sYear, sHour, sMin, sSec
sMon = AddZero(Month(Now))
sDay = AddZero(Day(Now))
sYear = AddZero(Year(Now))
sHour = AddZero(Hour(Now))
sMin = AddZero(Minute(Now))
sSec = AddZero(Second(Now))
GetTimeStampString = sMon&"_"&sDay&"_"&sYear&"__"&sHour&"_"&sMin&"_"&sSec
End Function


Sub PrintMsg(strMessage)
WScript.StdOut.Write vbCrLf & strMessage
End Sub
End Class

Class EnvironmentClass
Private objShell
Private strLogonServer
Private strProgramFiles
Private strProgramFilesX86
Private strUserProfile
Private strAllUsersProfile
Private strWinDir
Private strTempDir


Private Function GetEnvironmentValue(environmentVariable)
Dim fValue
fValue = objShell.ExpandEnvironmentStrings(environmentVariable)
GetEnvironmentValue = Replace(fValue, environmentVariable, "")
End Function


Public Cache


Public Property Let Shell(objParentShell)
Set objShell = objParentShell
End Property


Public Property Get LogonServer
If IsNull(strLogonServer) OR Cache = False Then strLogonServer = GetEnvironmentValue("%LOGONSERVER%")
LogonServer = strLogonServer
End Property


Public Property Get ProgramFiles
If IsNull(strProgramFiles) OR Cache = False Then strProgramFiles = GetEnvironmentValue("%PROGRAMFILES%")
ProgramFiles = strProgramFiles
End Property


Public Property Get ProgramFilesX86
If IsNull(strProgramFilesX86) OR Cache = False Then strProgramFilesX86 = GetEnvironmentValue("%PROGRAMFILES(x86)%")
ProgramFilesX86 = strProgramFilesX86
End Property


Public Property Get UserProfile
If IsNull(strUserProfile) OR Cache = False Then strUserProfile = GetEnvironmentValue("%USERPROFILE%")
UserProfile = strUserProfile
End Property


Public Property Get AllUsersProfile
If IsNull(strAllUsersProfile) OR Cache = False Then strAllUsersProfile = GetEnvironmentValue("%ALLUSERSPROFILE%")
AllUsersProfile = strAllUsersProfile
End Property


Public Property Get WinDir
If IsNull(strWinDir) OR Cache = False Then strWinDir = GetEnvironmentValue("%WINDIR%")
WinDir = strWinDir
End Property


Public Property Get TempDir
If IsNull(strTempDir) OR Cache = False Then strTempDir = GetEnvironmentValue("%TEMP%")
TempDir = strTempDir
End Property


Private Sub Class_Initialize()
Cache = True
strLogonServer = Null
strProgramFiles = Null
strProgramFilesX86 = Null
strUserProfile = Null
strAllUsersProfile = Null
strWinDir = Null
strTempDir = Null
End Sub
End Class

Link to comment
Share on other sites

Returns a time and date string - I use it when creating folders, usually. For example, the following line of script...:

WScript.Echo ScriptHelper.GetTimeStampString

...produces the following output:

09_22_2010__14_12_50

Here's an example snippet of how I tend to use it:

'// Gets the local computer name
strComputer = ScriptHelper.Network.ComputerName

'// Creates a string with the local computer name and the time/date, no spaces
strDataFold = strComputer & "_" & ScriptHelper.GetTimeStampString

'// Creates a string that paths to the current directory where the script is running, + "Folder", + the computername/time/date string folder:
strLocalDataStore = ScriptHelper.ScriptPath() & "\Folder\" & strDataFold

'// Creates the folder using the above string if it doesn't already exist:
If Not ScriptHelper.FileSystem.FolderExists(strLocalDataStore) Then
ScriptHelper.CreateFolder(strLocalDataStore)
Else
'The folder already exists
End If

So, with the script run from the desktop logged on as a user named "User", on a computer named "COMPUTERNAME", strLocalDataStore...

WScript.Echo "strLocalDataStore: " & strLocalDataStore

...would be:

strLocalDataStore: C:\Users\User\Desktop\Folder\COMPUTERNAME_09_22_2010__14_24_56

Link to comment
Share on other sites

Thanks Cluberti, I continue to learn from you from every post.

Thanks man you made my roll-out seamless

Returns a time and date string - I use it when creating folders, usually. For example, the following line of script...:

WScript.Echo ScriptHelper.GetTimeStampString

...produces the following output:

09_22_2010__14_12_50

Here's an example snippet of how I tend to use it:

'// Gets the local computer name
strComputer = ScriptHelper.Network.ComputerName

'// Creates a string with the local computer name and the time/date, no spaces
strDataFold = strComputer & "_" & ScriptHelper.GetTimeStampString

'// Creates a string that paths to the current directory where the script is running, + "Folder", + the computername/time/date string folder:
strLocalDataStore = ScriptHelper.ScriptPath() & "\Folder\" & strDataFold

'// Creates the folder using the above string if it doesn't already exist:
If Not ScriptHelper.FileSystem.FolderExists(strLocalDataStore) Then
ScriptHelper.CreateFolder(strLocalDataStore)
Else
'The folder already exists
End If

So, with the script run from the desktop logged on as a user named "User", on a computer named "COMPUTERNAME", strLocalDataStore...

WScript.Echo "strLocalDataStore: " & strLocalDataStore

...would be:

strLocalDataStore: C:\Users\User\Desktop\Folder\COMPUTERNAME_09_22_2010__14_24_56

Edited by clivebuckwheat
Link to comment
Share on other sites

Create an account or sign in to comment

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

Create an account

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

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...