Checking and opening different browsers using wsh script - shell

hey guys i know this may sound stupid, but i am stuck with this question in my head...im really new to this wscript or vbscripting....at the time of writing i figured out how to open IE using wscript...heres the code
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("iexplore.exe www.bbc.co.uk", 1)
but i cant figure out how to check if firefox is installed, then open firefox, if chrome is installed, open chrome, and the same thing goes for all the browser types.....
Update:
I did a little research and thought why not check the registry for that, so i came up with this script for checking the registry, now i dont know why but this always gives the same output "key does not exists" event though i have this registry in my system
keyTest = keyExists("HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox")
If keyTest = False Then
wscript.echo "Key does not exist"
Elseif keyTest = True then
wscript.echo "Key exists"
End if
Function keyExists (RegistryKey)
If (Right(RegistryKey, 1) <> "\") Then
RegistryKeyExists = false
Else
On Error Resume Next
WshShell.RegRead RegistryKey
Select Case Err
Case 0:
keyExists = true
Case &h80070002:
ErrDescription = Replace(Err.description, RegistryKey, "")
Err.clear
WshShell.RegRead "HKEY_ERROR\"
If (ErrDescription <> Replace(Err.description, _
"HKEY_ERROR\", "")) Then
keyExists = true
Else
RegistryKeyExists = false
End If
Case Else:
keyExists = false
End Select
On Error Goto 0
End If
End Function

Problems in your example:
In keyExists(), a variable named RegistryKeyExists is being used for the return value from the function when keyExists is intended.
The Shell object variable WshShell is never instantiated via CreateObject().
The value of the registry key of interest does not end with a backslash.
Here's my streamlined version of your code which I believe accomplishes your objective:
Option Explicit ' programming with your seatbelt on :-)
Dim keys(4)
keys(0) = "HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox"
keys(1) = "HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox\"
keys(2) = "HKEY_LOCAL_MACHINE\Bad\Key\"
keys(3) = "BAD\Root\On\This\Key\Causes\Exception"
keys(4) = "HKLM\SOFTWARE\Microsoft\Internet Explorer\"
On Error Resume Next
Dim i, key
For i = 0 To UBound(keys)
key = keyExists(keys(i))
If Err Then
WScript.Echo "An exception occurred reading registry key" _
& " '" & keys(i) & "':" _
& " [" & Err.Number & "] " _
& Err.Description _
& ""
Else
If keyExists(keys(i)) Then
WScript.Echo "Key *exists*: [" & keys(i) & "]"
Else
WScript.Echo "Key does *not* exist: [" & keys(i) & "]"
End If
End If
WScript.Echo "--"
Next
Function keyExists (RegistryKey)
Dim keyVal, errNum, errDesc
keyExists = False
On Error Resume Next
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
keyVal = WshShell.RegRead(RegistryKey)
Select Case Err
Case 0
keyExists = True
Case &h80070002
' key does not exist
Case Else
errNum = Err.Number
errDesc = Err.Description
On Error GoTo 0
Err.Raise vbObjectError + 1, "WScript.Shell", _
"Something went wrong reading the registry:" _
& " [" & Hex(errNum) & "] " & errDesc
End Select
On Error GoTo 0
Set WshShell = Nothing
End Function
' End

Generally following code can be used to find out to get List of All Installed Software.
Here I have used Message box to display this list, you can use if condition to find out desired software is installed or not............
' List All Installed Software
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
strComputer = "."
strKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
strEntry1a = "DisplayName"
Set objReg = GetObject("winmgmts://" & strComputer & _
"/root/default:StdRegProv")
objReg.EnumKey HKLM, strKey, arrSubkeys
For Each strSubkey In arrSubkeys
intRet1 = objReg.GetStringValue(HKLM, strKey & strSubkey, _
strEntry1a, strValue1)
If strValue1 <> "" Then
MsgBox VbCrLf & "Display Name: " & strValue1
End If
Next
I have tried this code on machine & found that,it just listing Firefox browser, even when i have installed chrome & IE.So this regular method wont work surely for everyone. After that I have checked registry and found that,all browser are listed on.....
HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet\
So we can write code to find is is particular browser is installed or not.
Following sample code to check if Chrome & Firefox is installed or not and if installed open it with URL passed
Set WshShell = CreateObject("WScript.Shell")
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Clients\StartMenuInternet\chrome.exe\shell\open\command\"
strValueName = ""
oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
If InStr(1,strValue,"chrome",vbTextCompare) Then WshShell.Run("chrome www.google.com")
strKeyPath = "SOFTWARE\Clients\StartMenuInternet\FIREFOX.EXE\shell\open\command\"
strValueName = ""
oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
If InStr(1,strValue,"firefox",vbTextCompare) Then WshShell.Run("firefox www.google.com")
Similarly you can modify this code for IE, Opera & Safari
Hope this helps.......

Related

VBScript MapNetworkDrive Error Handling

I am attempting to write a small script in VBScript just purely for my home use, which is run prior to a scheduled backup in Macrium Reflect.
I am stuck on one seemingly small issue and that is error handling when the Network Drive is physically disconnected, i.e. the cable is not attached.
At the moment the script check to see if the Drive is already attached, if the drive is not attached then a message is displayed telling the user to connect the cable and press YES.
Now, all things being well the user would have connected the cable as asked and then pressed the YES button but I want to catch the times when YES was pressed before attaching the drive's cable.
Within the code there's an 'On Error Resume Next' which masks this eventuality, so I comment out this line & indeed I get an Error 'The Network Path Was Not Found' on line 40:
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath, _
I want to use this caught error to display an alert to the user that the drive has not yet been connected, please connect and retry & KEEP RETRYING until the drive is actually connected.
My problem is I cannot seem to find where to add any error handling code to display this message.
Here's my code:
Option Explicit
Dim strDriveLetter, strRemotePath, strUser, strPassword, strProfile, strName, objNetwork, objShell, CheckDrive, AlreadyConnected, intDrive
' The section sets the variables.
strDriveLetter = "X:"
strRemotePath = "\\192.168.1.1\shared"
strUser = "user"
strPassword = "password"
strProfile = "true"
strName = "Backup Drive"
' This sections creates two objects:
' objShell and objNetwork and counts the drives
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Set CheckDrive = objNetwork.EnumNetworkDrives()
' This section deals with a For ... Next loop
' See how it compares the enumerated drive letters
' with strDriveLetter
On Error Resume Next
AlreadyConnected = False
For intDrive = 0 To CheckDrive.Count - 1 Step 2
If CheckDrive.Item(intDrive) =strDriveLetter _
Then AlreadyConnected = True
Next
If AlreadyConnected = False Then
Dim result
result = MsgBox("A Backup Is Now Due But The Drive Is Not Connected." & vbNewLine & vbNewLine & "Please Connect The Drive & Press YES To Continue." & vbNewLine & vbNewLine & "If You Wish To Postpone Backup Then Press NO Now.", 4 + 32, "BACKUP DRIVE NOT CONNECTED")
If result = 7 Then
WScript.Quit
Else
Call MapDRV
End If
Sub MapDRV()
Set objNetwork = WScript.CreateObject("WScript.Network")
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath, _
strProfile, strUser, strPassword
Set objShell = CreateObject("Shell.Application")
objShell.NameSpace(strDriveLetter).Self.Name = strName
End Sub
WScript.Quit
The error handling code is something along these lines:
If Err.Number <> 0 Then
'error handling:
'ALERT USER HERE
Err.Clear
End If
Any help would be appreciated
Err Object (VBScript) reference does not give useful guide. You need to trap an error or success separate for every run-time error prone action.
Common rule (best practice): keep error handling disabled via On Error GoTo 0 and enable it only for suspected actions.
For instance, there could me more than one reason why MapNetworkDrive method could fail (server off-line, user blocked, wrong/changed password etc.):
Sub MapDRV
Dim errResult
Set objNetwork = WScript.CreateObject("WScript.Network")
errResult = ""
On Error Resume Next
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath _
, strProfile, strUser, strPassword
If Err.Number = 0 Then
On Error GoTo 0
Set objShell = CreateObject("Shell.Application")
objShell.NameSpace(strDriveLetter).Self.Name = strName
Else
errResult = Err.Number & " 0x" & Hex(Err.Number) & " " & Err.Source
errResult = errResult & vbNewLine & Err.Description
On Error GoTo 0
MsgBox errResult, vbOKOnly + vbCritical, "Error occurred"
End If
End Sub
The whole script then could look as follows:
Option Explicit
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim strDriveLetter, strRemotePath, strUser, strPassword, strProfile , strName _
, objNetwork, objShell, CheckDrive, AlreadyConnected, intDrive
' The section sets the variables.
strDriveLetter = "X:"
strRemotePath = "\\192.168.1.1\shared"
strUser = "user"
strPassword = "password"
strProfile = "true"
strName = "Backup Drive"
' This sections creates two objects:
' objShell and objNetwork and counts the drives
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
' This section deals with a For ... Next loop
' See how it compares the enumerated drive letters with strDriveLetter
Dim result, toShare
AlreadyConnected = False
Do While AlreadyConnected = False
strResult = strResult & vbNewLine & "--- new check"
AlreadyConnected = False
Set CheckDrive = objNetwork.EnumNetworkDrives()
For intDrive = 0 To CheckDrive.Count - 1 Step 2
If CheckDrive.Item(intDrive) = strDriveLetter Then
AlreadyConnected = True
toShare = CheckDrive.Item(intDrive + 1)
End If
strResult = strResult & vbNewLine & CheckDrive.Item(intDrive)
strResult = strResult & vbTab & CheckDrive.Item(intDrive + 1)
Next
If AlreadyConnected Then Exit Do
result = MsgBox("A Backup Is Now Due But The Drive Is Not Connected." _
& vbNewLine & vbNewLine & "If you wish to ..." _
& vbNewLine & vbTab & "... postpone backup then press ABORT." _
& vbNewLine & vbTab & "... backup to " & strRemotePath & " then press RETRY." _
& vbNewLine & "Otherwise, please connect the drive & press IGNORE to continue." _
, vbAbortRetryIgnore + vbQuestion, "BACKUP DRIVE NOT CONNECTED")
Select Case result
Case vbAbort
Call scriptQuit
Case vbRetry
Call MapDRV
Case Else
' The Case Else clause is not required
End Select
Loop
strResult = strResult & vbNewLine & "copy here to " & toShare
Sub MapDRV
' no need to redefine: WshNetwork Object is already defined
' Set objNetwork = WScript.CreateObject("WScript.Network")
Dim errResult
On Error Resume Next
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath _
, strProfile, strUser, strPassword
If Err.Number = 0 Then
On Error GoTo 0
Set objShell = CreateObject("Shell.Application")
objShell.NameSpace(strDriveLetter).Self.Name = strName
Else
errResult = Err.Number & " 0x" & Hex(Err.Number) & " " & Err.Source
errResult = errResult & vbNewLine & Err.Description
On Error GoTo 0
MsgBox errResult, vbOKOnly + vbCritical, "Error occurred"
strResult = strResult & vbNewLine & vbNewLine & errResult
End If
End Sub
Call scriptQuit
Sub scriptQuit
Wscript.Echo strResult
Wscript.Quit
End Sub
Please note that strResult variable is there merely for debugging purposes to see next output:
==> cscript D:\VB_scripts\SO\37776762.vbs
37776762.vbs
--- new check
Y: \\S-PC\VB_scripts_help
-2147024843 0x80070035 WSHNetwork.MapNetworkDrive
The network path was not found.
--- new check
Y: \\S-PC\VB_scripts_help
--- new check
Y: \\S-PC\VB_scripts_help
X: \\S-PC\test
copy here to \\S-PC\test
==>
Above output corresponds to next actions:
run script
1st --- new check found Y: mapped disk; then invoked Retry action failed (network path was not found);
2nd --- new check found Y: mapped disk again; then mapped disk X: manually and then invoked Ignore action;
3rd --- new check found Y: and X: mapped disks;
Do While loop exited and script continues to next action.
For completeness, following output shows invoked Abort action:
==> net use x: /delete
x: was deleted successfully.
==> cscript D:\VB_scripts\SO\37776762.vbs
37776762.vbs
--- new check
Y: \\S-PC\VB_scripts_help
==>

create folder(trusted), copy of MDE and shortcut

I have put together a script that I think will work, but the only code I know is some VBA. Never tried to create a vbscript before, so my apologies if some errors are obvious, but pointers and corrections would be appreciated.
I am hoping I can give users in my company a link to this script and have them run it. It will create a folder on their C Drive, make it a trusted location, copy a database frontend from the server into it and create a shortcut on their desktop linking to the new file. (I'm hoping the file will auto-update when a new version is made - I think that bit works though).
The code comes from various sources, including my own addled mind but would I need to download Visual Studio to test this? Slightly concerned as it includes creating a registry key and I don't know how to stop the code if it all goes horribly wrong. I don't even know how to break a loop (although I think I read somewhere you need to hit Esc twice). Any tips on how to signify which sub is the main one to run on start would be good too.
EDIT : Code has been amended to my end result incase it is of use to others. Please use with caution. The 'update' vbs deletes the folder created on the local drive.
'FrontEnd Setup
call CreateTrustedFolder
'Const HKEY_CLASSES_ROOT = &H80000000
Const HKEY_CURRENT_USER = &H80000001
'Const HKEY_LOCAL_MACHINE = &H80000002
'Const HKEY_USERS = &H80000003
'Const HKEY_CURRENT_CONFIG = &H80000005
Dim lclFolder
Dim blnUpdate
Sub CreateTrustedFolder()
On error resume next
Call RunAdmin
Call FolderFileShortcut
Call CreateReg
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
'Run as Administrator
Sub RunAdmin()
On error resume next
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
'Check if folder exists, add file and desktop shortcut
Sub FolderFileShortcut()
On error resume next
Dim oWS
Dim FSO
Dim svrFolder
Dim myShortcut
Dim strLocalDB
Dim strServerDB
Dim strUpdate
Dim strIcon
Dim objFile
Dim counter
Set oWS = WScript.CreateObject("WScript.Shell")
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
svrFolder = "\\192.168.1.2\DeptFolder\DatabaseFolder\Auto-Update"
lclFolder = "C:\Program Files\Orrible Database"
If (FSO.FolderExists(lclFolder)) Then
oWS.run "icacls """ & lclFolder & """ /reset /grant:r Users:(W) /t" '/T required for existing folders
FSO.DeleteFolder lclFolder
blnUpdate = True
end if
If Not (FSO.FolderExists(svrFolder)) Then
msgbox "Unable to connect to Location Server", vbCritical, "Installation Failed"
WScript.Quit
End If
For Each objFile in FSO.Getfolder(svrFolder).Files
if LCase(FSO.GetExtensionName(objFile.name)) = LCase("mde") then
counter = counter + 1
strServerDB = FSO.GetFileName(objFile)
end if
Next
If strServerDB = "" or counter <> 1 then
msgbox "Unable to locate the Front End" & strServerDB & "-" & counter, vbCritical, "Installation Failed"
wScript.Quit
end if
strLocalDB = "Co Database.mde"
strUpdate = "DB_UpdateCheck.vbs"
strIcon = "Frontend Update.ico"
FSO.CreateFolder(lclFolder)
oWS.run "icacls """ & lclFolder & """ /grant Users:(OI)(CI)F /t" '/T required for existing folders
FSO.CopyFile svrFolder & "\" & strUpdate, lclFolder & "\" & strUpdate, True
FSO.CopyFile svrFolder & "\" & strServerDB, lclFolder & "\" & strLocalDB, True
FSO.CopyFile svrFolder & "\" & strIcon, lclFolder & "\" & strIcon, True
strDesktop = oWS.SpecialFolders("Desktop")
set myShortcut = oWS.CreateShortcut(strDesktop + "\New Database.lnk")
myShortcut.TargetPath = lclFolder & "\" & strUpdate
myShortcut.WindowStyle = 1
myShortcut.IconLocation = lclFolder & "\" & strIcon
myShortcut.WorkingDirectory = strDesktop
myShortcut.Save
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
Sub CreateReg()
On error resume next
Dim objRegistry 'registry object
Dim strDescription 'Description of the Trusted Location
Dim strParentKey 'Registry location of Application
Dim strNewKey 'strParentKey and myFolder
Dim oWS 'WSH shell object
strDescription = "DB Folder"
strParentKey = "Software\Microsoft\Office\15.0\Access\Security\Trusted Locations"
strNewKey = strParentKey & "\" & strDescription & "\"
Set objRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv")
'objRegistry.GetStringValue HKEY_CURRENT_USER, strParentKey & "\" & strDescription
If Not objRegistry.EnumKey(HKEY_CURRENT_USER, strNewKey) = 0 then '0=true
objRegistry.CreateKey HKEY_CURRENT_USER, strNewKey
objRegistry.SetStringValue HKEY_CURRENT_USER, strNewKey, "Path", lclFolder
objRegistry.SetStringValue HKEY_CURRENT_USER, strNewKey, "Description", strDescription
End if
If not blnUpdate = True then
msgbox "The Database is now available from your desktop", vbInformation, "Setup Complete"
Else
msgbox "The update is now complete."
End if
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
There is also a separate Update vbs which is what runs when the link is clicked. This checks to see if the 'created date' of the database on the server is newer than that on the local drive. The new DB name MUST NOT be the same as the one it is replacing. It might run a little fast, but this is as far as I have taken this.
Call CheckForUpdate
Sub CheckForUpdate()
On Error Resume Next
Dim FSO
Dim oWS
Dim svrFolder
Dim lclFolder
Dim svrFail
Dim strLocalDB
Dim strServerDB
Dim lclDate
Dim svrDate
Dim strFileName
Dim intDBcount
Dim fCheck
Set oWS = WScript.CreateObject("WScript.Shell")
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
svrFolder = "\\192.168.1.2\DeptFolder\DatabaseFolder\Auto-Update"
lclFolder = "C:\Program Files\Orrible Database"
strLocalDB = "Co Database.mde"
If Not (FSO.FolderExists(svrFolder)) Then
msgbox "Unable to connect to Location Server", vbCritical, "Update Check Failed"
svrFail = True
End If
If Not svrFail = True Then
For Each fCheck in FSO.GetFolder(svrFolder).Files
If Ucase(Right(fCheck.Name, 3)) = "MDE" Then
intDBcount = intDBcount + 1
strServerDB = fCheck.name
End If
Next
If Not intDBcount = 1 Then
MsgBox "Please inform the Administrator that there is a problem with the Automated Update System.", _
vbCritical, "Update Failed (" & intDBcount & ")"
svrFail = True 'not quit - need to see if old version available
End If
End If
If Not (FSO.FolderExists(lclFolder)) Then
If svrFail = True Then 'If no lcl folder or server
If Not intDBcount = 1 then WScript.Quit
msgbox "You are unable to use the Database." & vbcrlf & _
"Please try again when you have access to the Location Server.", _
vbcritical, "Database Not Installed"
WScript.Quit
Else 'If no lclfolder, get it from svr
'Do normal initial install
oWS.Run svrFolder & "\" & "DB_Install.vbs", 1, True
WScript.Quit
End If
Else
If svrFail = True Then 'If lcl folder, but no svr
'open db
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
Else 'If lcl folder and svr access, check for update.
lclDate = fso.getfile(lclFolder & "\" & strLocalDB).DateCreated
svrDate = fso.getfile(svrFolder & "\" & strServerDB).DateCreated
If lclDate < svrDate Then 'Update available
intMsg = MsgBox("An update is available - Do you wish to update now?", vbQuestion + vbYesNo, "Update Found")
If intMsg = vbYes Then
oWS.Run svrFolder & "\" & "DB_Install.vbs", 1, True ',1,true should pause the code until install closes
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
Else
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
End If
Else
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
End If
End If
End If
If err Then
MsgBox "The following error has occurred " & Err & " " & Err.Description
Exit Sub
End If
End Sub

VBScript: How to add a HEX value into a registry key?

binary data to insert(from .reg file):
"FailureActions"=hex:00,00,00,00,00,00,00,00,00,00,00,00,03,00,00,00,14,00,00,\
00,01,00,00,00,60,ea,00,00,01,00,00,00,60,ea,00,00,00,00,00,00,00,00,00,00
MSDN says: "RegWrite will write at most one DWORD to a REG_BINARY value. Larger values are not supported with this method."
wshShell.RegWrite "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Service1\FailureActions", hexValueHere, "REG_BINARY"
I am trying to avoid calling Regedit and importing a .reg file. I just need to add "FailureActions" key with the proper hex value mentioned above.
Any ideas? Here is my latest code which is still NOT working. :-(
Option Explicit
Call SetServiceFailureActions()
Sub SetServiceFailureActions()
Const HKEY_LOCAL_MACHINE = &H80000002
Set objRegistry=GetObject( _
"winmgmts:{impersonationLevel=impersonate}!\\" & _
"." & "\root\default:StdRegProv")
Dim path
path = "SYSTEM\CurrentControlSet\Services\Service1\FailureActions"
Dim hexValues, arrHexValues, arrDecValues
hexValues = "hex:00,00,00,00,00,00,00,00,00,00,00,00,03,00,00,00,14,00,00,00,01,00,00,00,60,ea,00,00,01,00,00,00,60,ea,00,00,00,00,00,00,00,00,00,00"
arrHexValues = Split(Replace(hexValues, "hex:", ""), ",")
arrDecValues = DecimalNumbers(arrHexValues)
Dim objRegistry, Return
Return = objRegistry.SetBinaryValue(HKEY_LOCAL_MACHINE, path, "FailureActions", arrDecValues)
If (Return = 0) And (Err.Number = 0) Then
Wscript.Echo "Registry key value for [FailureActions] has been added successfully."
Else
' An error occurred
Wscript.Echo "ERROR when setting the value for the registry key: [FailureActions]."
WScript.Echo "Exception:" & vbCrLf &_
"Error number: " & Err.Number & vbCrLf &_
"Error description: '" & Err.Description & vbCrLf
End If
End Sub
Function DecimalNumbers(arrHex)
Dim i, strDecValues
For i = 0 to Ubound(arrHex)
If isEmpty(strDecValues) Then
strDecValues = CLng("&H" & arrHex(i))
'WScript.Echo "strDecValues: " & strDecValues
Else
strDecValues = strDecValues & "," & CLng("&H" & arrHex(i))
'WScript.Echo "strDecValues: " & strDecValues
End If
next
DecimalNumbers = split(strDecValues, ",")
End Function
Thank you
You can use the WMI Registry Provider's SetBinaryValue method, as long as you don't have to support Windows XP: however note that this must run as an elevated process as it's a protected key:
Const HKEY_LOCAL_MACHINE = &H80000002
Set objRegistry = GetObject("Winmgmts:root\default:StdRegProv")
path = "SYSTEM\CurrentControlSet\Services\Service1"
values = Array(128,81,1,0,0,0,0,0) ' etc
Return = objRegistry.SetBinaryValue(HKEY_LOCAL_MACHINE, _
path, "FailureActions", values)
If (Return = 0) And (Err.Number = 0) Then
Wscript.Echo "Binary value added successfully"
Else
' An error occurred
End If

"Less than" statements not evaluating

Running into this problem. Trying to uninstall all previous version of a program using the less than statement and installing new version. It doesn't recognize the less than and will keep uninstalling and reinstalling the newest version everytime.
Option Explicit
Const HKEY_LOCAL_MACHINE = &H80000002
Dim Msg, MsgBoxStyle, RegKey, NAMProductKey, NAMProductName, NAMVersion
'=== START Check for Cisco AnyConnect Network Access Manager < 3.1.05170
Sub GetNAMKey()
Dim oReg, sPath, aKeys, sName, sKey, sVersion
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
sPath = "SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
oReg.EnumKey HKEY_LOCAL_MACHINE, sPath, aKeys
For Each sKey in aKeys
oReg.GetStringValue HKEY_LOCAL_MACHINE, sPath & "\" & sKey, "DisplayName", sName, "DisplayVersion", sVersion
If Not IsNull(sName) Then
If (sName = "Cisco AnyConnect Network Access Manager") Then
NAMProductKey = sKey
NAMProductName = sName
NAMVersion = sVersion
End If
End If
Next
End Sub
'=Start Uninstall Reference==
Sub UninstallUNI(key, name)
Dim cmd, objShell, iReturn, oshell
cmd = "%SystemRoot%\System32\msiexec.exe /q/x " & key
Set objShell = wscript.createObject("wscript.shell")
objShell.LogEvent 0, "Removing the program [" & name & "] under Product Key [" & key & "]" & vbCrLf & "Executing command: " & vbCrLf & cmd
iReturn=objShell.Run(cmd,1,TRUE)
If (iReturn = 0) Then
objShell.LogEvent 0, "Program [" & name & "] was successfully removed"
Else
objShell.LogEvent 0, "Failed to remove the program [" & name & "]."
End If
Set objShell = Nothing
End Sub
'=== START CALLs (This is the script's logic.)
Dim objWSH
Set objWSH = CreateObject("WScript.Shell")
NAMProductKey = ""
NAMProductName = ""
NAMVersion = ""
Call GetNAMKey()
If Not (NAMProductKey = "") Then
If (NAMVersion < "3.1.05170") Then
Call UninstallUNI
NAMProductKey = ""
NAMProductName = ""
NAMVersion = ""
Call GetNAMKey()
If (NAMProductKey = "") Then
'Now we need to produce "msiexec.exe /a "Msi file.msi" /quiet /norestart" for a silent MSI install
objWSH.Run "msiexec.exe /i " + Chr(34) + "C:\Users\sek\Music\Cisco ISE\AnyConnect Network Access Manager\anyconnect-nam-win-3.1.05170-k9.msi" + Chr(34) + " /quiet /norestart"
End If
End If
Else
'Now we need to produce "msiexec.exe /a "Msi file.msi" /quiet /norestart" for a silent MSI install
objWSH.Run "msiexec.exe /i " + Chr(34) + "C:\Users\sek\Music\Cisco ISE\AnyConnect Network Access Manager\anyconnect-nam-win-3.1.05170-k9.msi" + Chr(34) + " /quiet /norestart"
End If
Unless you have very specific knowledge about how Cisco names it's versions you can not compare them like this.
The method you are using is a string compare which follows some lexicographic standard rules.
Because of that a version umber like 3.2 will be considered greater than 3.10.
In order to fix this you will have to split the string with '.' as delimiter and compare the subversion numbers independently.
However this is more a general observation and not the direct reason for the wrong evaluation.
I think the reason for that lies within your GetStringValue call.
According to the API this method can not return 2 values at once, so I am a bit puzzled how this is even executed without error. It explains however why the version number is not returned correctly. You would need a second GetStringValue call for that.

Skipping computers with error

I'm having an issue with a VBScript that looks for printers on computers from a list on an Excel sheet and then finds them through WMI. It matches them through the IP address name and then writes a batch file that I can install them from. My issue is that when I have a computer that is turned off I get a 462 error which is then cleared but then the printers for the previous computer are written again. I'm quite new at this so I'm not sure if I'm just missing something really basic here.
Batch = "printerOutput.txt"
Const ForWriting = 2 'Set to 8 for appending data
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(Batch, ForWriting)
On Error Resume Next
Dim printerDictionary 'Create Printer dictionary of names and IP addresses
Set printerDictionary = CreateObject("Scripting.Dictionary")
printerDictionary.Add "Printer","xxx.xxx.xxx.xxx"
Set objExcel_1 = CreateObject("Excel.Application")
' Statement will open the Excel Workbook needed.
Set objWorkbook = objExcel_1.Workbooks.Open _
("x\p.xls")
If Err.Number <> 0 Then
MsgBox "File not Found"
Wscript.Quit
End If
'Checks for errors
f = 1 'Sets variable that will loop through Excel column
Do
' Msgbox f,, "Begining of Do Loop"
strComputer = objExcel_1.Cells(f, 1).Value
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colPrinters = objWMIService.ExecQuery("Select * From Win32_Printer")
For Each objPrinter in colPrinters 'For ever objPrinter found in the computers WMIService
If Err.Number = 0 Then
objFile.WriteLine Err.Number
If InStr(ObjPrinter.PortName,".") = 4 then 'If the printers IP port name is written like 128.xxx.xxx.xxx
'MsgBox ObjPrinter.Name & " " & ObjPrinter.PortName,, "IfStatement"
PrtDict ObjPrinter.PortName, StrComputer
ElseIf InStr(ObjPrinter.PortName,"_") = 3 Then 'If the printers IP port name is written like IP_128.xxx.xxx.xxx
cleanIP = GetIPAddress(objPrinter.PortName) 'Clean IP
PrtDict cleanIP, StrComputer
End If
Else
objFile.WriteLine "REM " & strComputer & " - Error: " & err.number
Err.Clear
End If
Next
f = f + 1
Loop Until objExcel_1.Cells(f, 1).Value = ""
objExcel_1.ActiveWorkbook.Close
ObjExcel_1.Quit
Function PrtDict(PrtMn, CMP) 'Loops through the dictionary to find a match from the IP address found
For Each x in printerDictionary
'MsgBox PrtMn & "=" & printerDictionary.Item(x),,"InPtrDict"
If printerDictionary.Item(x) = PrtMn Then
objFile.WriteLine "psexec -u \%1 -p %2 " & CMP & " path\" & x & ".bat"
End If
Next
End Function
'100
Function GetIPAddress(Address) 'For cleaning up IP address with names like IP_128.xxx.xxx.xxx
IPtext = InStr(Address,"_")
IPaddress = len(Address) - IPtext
GetIPAddress = Right(Address,IPaddress)
End Function
What happens is this:
On Error Resume Next
This enables error-handling (or rather error suppression) for the rest of the script, since it's never disabled.
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
This command fails, because strComputer is not reachable. Because of the error the variable Err is set and objWMIService retains its previous value.
Set colPrinters = objWMIService.ExecQuery("Select * From Win32_Printer")
This command succeeds and re-reads the printer list from the previous computer, because objWMIService still refers to that computer.
For Each objPrinter in colPrinters
The script enters the loop, because colPrinters got populated with the printers from the previous computer (again), …
If Err.Number = 0 Then ... Else ... End If
… but because Err is still set, the script goes into the Else branch, where the error is reported and cleared:
objFile.WriteLine "REM " & strComputer & " - Error: " & err.number
Err.Clear
Then the script goes into the next iteration of the loop. Err is now cleared, so the rest of the printers in colPrinters is being processed normally.
Global On Error Resume Next is the root of all evil. Don't do this. EVER.
If you absolutely must use On Error Resume Next, enable error-handling locally, put some actual error handling code in place, and disable error-handling right afterwards. In your case one might implement it like this:
...
Do
strComputer = objExcel_1.Cells(f, 1).Value
On Error Resume Next
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
If Err Then
objFile.WriteLine "REM " & strComputer & " - Error: " & err.number
Set objWMIService = Nothing
End If
On Error Goto 0
If Not objWMIService Is Nothing Then
Set colPrinters = objWMIService.ExecQuery("Select * From Win32_Printer")
For Each objPrinter in colPrinters
...
Next
f = f + 1
End If
Loop Until objExcel_1.Cells(f, 1).Value = ""
...

Resources