Trying to create a key in registry database - vbscript

I have done this code, but it seems that it dosen't work. I don't why. I have searched on google, but no luck. :(
Set objREG = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
Const HKEY_LOCAL_MACHINE = &H80000002
Dim lstrKeyPath, lstrValueName, lstrValue
lstrKeyPath = "SOFTWARE\Canon\GARO1\"
lstrValueName = "LocaleInfo"
objReg.GetStringValue HKEY_LOCAL_MACHINE,lstrKeyPath,lstrValueName,lstrValue
msgbox lstrValue <--- This works.
if IsNull(lstrValue) then
lstrKeyPath = lstrKeyPath & lstrValueName
else
lstrValueName = "LocaleTest"
lstrKeyPath = "Software\Test\"
Return = objReg.CreateKey(HKEY_LOCAL_MACHINE,lstrKeyPath)
if Return = 0 Then
msgbox "Yes"
else
msgbox "No"
end if
end if
Set OBJREG = Nothing
I can't see my "Test" key in the registry

I have used the following to check for and insert registry keys if they don't exist:
Dim WshShell, Test, blExists, DQ
Set WshShell = CreateObject("WScript.Shell")
DQ = chr(34)
RegKeyPath = "HKEY_CLASSES_ROOT\LFS\"
RegValueName = "URL:LFS Protocol"
Test = RegKeyExists(RegKeyPath,RegValueName)
If Test = False Then
WshShell.RegWrite RegKeyPath, "URL:LFS Protocol" ,"REG_SZ"
End If
'Function Returns False if the regkey isnt found otherwise it returns
'The registry key value specified
Function RegKeyExists(sRegKey,sRegValueName)
On Error Resume Next
Dim WSHShellRegTest, Test, blExists
Set WSHShellRegTest = CreateObject("WScript.Shell")
blTrueFalse = True
Test = WSHShellRegTest.RegRead (sregkey + sRegValueName)
If Err Then
RegKeyExists = False
Err.clear
Exit Function
End if
Set WSHShellRegTest = Nothing
RegKeyExists = Test
End Function

Related

Receiving error code 424 in VBA when attempting to use CopyHere method with built in Windows Zip

I am receiving the object required error on the following line, although fl4 is a defined variant/object/file:
oFold.CopyHere (fl4)
Any thoughts would be appreciated.
Below is an applicable excerpt of code. I have excluded the recursive loop and directory sub folder iteration:
srcpth = rs1.Fields("Src_File_Path").Value
destpth = rs1.Fields("Zip_File_Path").Value
var = 0
Set FS2 = New FileSystemObject
Set FS2 = CreateObject("Scripting.FileSystemObject")
Set fl1 = FS2.GetFolder(srcpth)
For Each fl2 In FS2.GetFolder(srcpth).SubFolders
var = 2
ZipFile = Application.CurrentProject.Path & "\tmp\" & fl2.Name & ".zip"
Set FS3 = CreateObject("Scripting.FileSystemObject")
FS3.CreateTextFile(ZipFile, True).Write Chr(80) & Chr(75) & Chr(5) & Chr(6) & String(18, 0)
Set FS3 = Nothing
Set FS4 = New FileSystemObject
Set FS4 = CreateObject("Scripting.FileSystemObject")
Set fl3 = FS4.GetFolder(fl2)
For Each fl4 In FS4.GetFolder(fl2).Files
var = 2
GoTo Zipxchg
zipxchg_2:
Next
Next
Set FS1 = Nothing
Set oFld = Nothing
Set oApp = Nothing
Set oShl = Nothing
Exit Sub
Zipxchg:
If var = 2 Then
ZipFile = Application.CurrentProject.Path & "\tmp\" & fl2.Name & ".zip"
Set oApp = CreateObject("Shell.Application")
Set oFld = oApp.NameSpace(CVar(ZipFile))
Set FilestoZip = objShell.File(fl4)
i = oFld.Items.Count
oFold.CopyHere (fl4)
Set oShl = CreateObject("WScript.Shell")
GoTo zipxchg_2
End Sub
remove the brackets .... use oFold.CopyHere fl4 .... brackets cause a value to be returned, but there is no variable (object) to receive it

Delete folder on multiple usb drives VBS

I am looking to delete folder on multiple usb driver at the same time.
sDeleteFolder = "\Test"
Set oFS = CreateObject("Scripting.FileSystemObject")
Set dUSBKeys = ScanForUSBKeys()
For Each oUSBKey in dUSBKeys.Keys
If Left(oUSBKey, 1) = "\" Then
sKey = oUSBKey
Else
sKey = oUSBKey & "\"
End If
oFS.DeleteFolder sdeleteFolder, sKey
Next
Set dUSBKeys = Nothing
Set oFS = Nothing
MsgBox "Done Del all the folder from USB Drivs", vbOKOnly+VBINformation+VBSystemModal, "DONE"
Function ScanForUSBKeys()
Set oWMI = GetObject("winmgmts:\\.\root\cimv2")
Set dTemp = CreateObject("Scripting.Dictionary")
Set cDisks = oWMI.ExecQuery("Select InterfaceType,MediaType,PNPDeviceID,DeviceID,Size from Win32_DiskDrive")
For Each oDisk in cDisks
If InStr(LCase(oDisk.InterfaceType),"usb") > 0 AND InStr(LCase(oDisk.MediaType),"removable") > 0 _
AND InStr(LCase(oDisk.PNPDeviceID),"blackberry") = 0 AND InStr(LCase(oDisk.PNPDeviceID),"ipod") = 0 _
AND NOT oDisk.PNPDeviceID = "" Then
Set cDrivePartitions = oWMI.ExecQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" & _
oDisk.DeviceID & "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition" )
For Each oDrivePartition in cDrivePartitions
Set cDriveLetters = oWMI.ExecQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" & _
oDrivePartition.DeviceID & "'} WHERE AssocClass = Win32_LogicalDiskToPartition")
For Each oDriveLetter in cDriveLetters
dTemp.Add oDriveLetter.DeviceID, 1
Next
Set cDriveLetters = Nothing
Next
Set cDrivePartitions = Nothing
End If
Next
Set cDisks = Nothing
Set ScanForUSBKeys = dTemp
Set dTemp = Nothing
Set oWMI = Nothing
End Function
I keep getting a error :
Type mismatch: 'oFs.DeleteFolder'
Line 12 Char 5
Study the docs for .DeleteFolder
Make sure you pass the full path (not just "\test") and the appropriate boolean (not a string like oUSBKey) when you call the Sub
Use .BuildPath to build that full path
Use the good features of VBScript. E.g.: Option Explicit, declare sPath as Const
Don't use Set x = Nothing in vain
Try this code
sDeleteFolder = "\Test"
For Each oUSBKey in dUSBKeys.Keys
sKey = oUSBKey & sDeleteFolder
oFS.DeleteFolder sKey
Next

Reset Network Adapter

I have here a VBScript to "toggle" my network adapter (built from a script found on the Internet).
I was wondering if maybe someone can help me convert it to a script that can "reset" (disable, then re-enable) my wireless adapter, rather than toggle it.
'~ Toggle a SPECIFIED NIC on or off
Option Explicit
Const NETWORK_CONNECTIONS = &H31&
Dim objShell, objFolder, objFolderItem, objEnable, objDisable
Dim folder_Object, target_NIC
Dim NIC, clsVerb
Dim str_NIC_Name, strEnable, strDisable
Dim bEnabled, bDisabled
'NIC name goes here VVV
str_NIC_Name = "Wi-Fi"
strEnable = "En&able"
strDisable = "Disa&ble"
' create objects and get items
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(NETWORK_CONNECTIONS)
Set objFolderItem = objFolder.Self
Set folder_Object = objFolderItem.GetFolder
Set target_NIC = Nothing
' look at each NIC and match to the chosen name
For Each NIC In folder_Object.Items
If LCase(NIC.Name) = LCase(str_NIC_Name) Then
' proper NIC is found, get it
Set target_NIC = NIC
End If
Next
bEnabled = True
Set objEnable = Nothing
Set objDisable = Nothing
For Each clsVerb In target_NIC.Verbs
'~ Wscript.Echo clsVerb
If clsVerb.Name = strEnable Then
Set objEnable = clsVerb
bEnabled = False
End If
If clsVerb.Name = strDisable Then
Set objDisable = clsVerb
End If
Next
If bEnabled Then
objDisable.DoIt
Else
objEnable.DoIt
End If
'~ Give the connection time to change
WScript.Sleep 5000
I think it's better to use WMI (Windows Management Instrumentation).
Here is a sample script:
Option Explicit
dim ComputerName
dim WMIService, NIC
dim ConnectionName
ComputerName = "."
ConnectionName = "Ethernet"
if not IsElevated then
WScript.Echo "Please run this script with administrative rights!"
WScript.Quit
end if
On Error Resume Next
Set WMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ComputerName & "\root\cimv2")
Set NIC = WMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID = '" & ConnectionName & "'").ItemIndex(0)
if NIC is nothing then
WScript.Echo "NIC not found!"
WScript.quit
end if
WScript.Echo "NIC Current status: " & iif(NIC.NetEnabled, "Enabled", "Disabled") & vbcrlf
if NIC.NetEnabled then
WScript.Echo "Disabling NIC..."
NIC.Disable
WScript.Sleep 1000
WScript.Echo "Enabling NIC..."
NIC.Enable
end if
function iif(cond, truepart, falsepart)
if cond then iif=truepart else cond=falsepart
end function
function IsElevated()
On Error Resume Next
CreateObject("WScript.Shell").RegRead("HKEY_USERS\s-1-5-19\")
IsElevated = (err.number = 0)
end function

Checking and opening different browsers using wsh script

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.......

How to check for registry value using VbScript

How can I check for registry value using VbScript?
Function ReadFromRegistry(strRegistryKey, strDefault)
Dim WSHShell, value
On Error Resume Next
Set WSHShell = CreateObject("WScript.Shell")
value = WSHShell.RegRead( strRegistryKey )
If err.number <> 0 Then
readFromRegistry = strDefault
Else
readFromRegistry = value
End If
Set WSHShell = Nothing
End Function
Usage :
str = ReadfromRegistry("HKEY_LOCAL_MACHINE\SOFTWARE\Adobe\ESD\Install_Dir", "ha")
WScript.echo "returned " & str
Original post
Try something like this:
Dim windowsShell
Dim regValue
Set windowsShell = CreateObject("WScript.Shell")
regValue = windowsShell.RegRead("someRegKey")
This should work for you:
Dim oShell
Dim iValue
Set oShell = CreateObject("WScript.Shell")
iValue = oShell.RegRead("HKLM\SOFTWARE\SOMETHINGSOMETHING")
Try this. This script gets current logged in user's name & home directory:
On Error Resume Next
Dim objShell, strTemp
Set objShell = WScript.CreateObject("WScript.Shell")
strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERNAME"
WScript.Echo "Logged in User: " & objShell.RegRead(strTemp)
strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERPROFILE"
WScript.Echo "User Home: " & objShell.RegRead(strTemp)
Set objShell = WScript.CreateObject("WScript.Shell")
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{9A25302D-30C0-39D9-BD6F-21E6EC160475}\"
with CreateObject("WScript.Shell")
on error resume next ' turn off error trapping
sValue = .regread(sKey) ' read attempt
bFound = (err.number = 0) ' test for success
end with
if bFound then
msgbox "exists"
else
msgbox "not exists"
End If

Resources