• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1537
  • Last Modified:

Check to see if Registry Key Exists, if it does Write Value to Different Registry Key

I would like to find out what the vb script is for Checking to see if an existing registry key exists and if it does, write a value to another registry key. If it doesn't do nothing. For example:
The path I want to check to see if it exists is

"HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Backup of Outlook"

If the above key exists, then run the below registry key, or enter the value of the "DefaultProfile" key to "Backup of Outlook"

"[HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles]
"DefaultProfile"="Backup of Outlook"
0
MGS-TECH
Asked:
MGS-TECH
  • 4
  • 3
  • 3
  • +1
2 Solutions
 
ThinkPaperIT ConsultantCommented:
for vbscript, here's some links for checking if a registry key exists...

http://www.tek-tips.com/faqs.cfm?fid=5864
http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/registry/#CreateStringDword.htm

If it does, you'd simply have to add some extra code after the IF statement
to add the values (assuming its a string)
I haven't tested this but should work...

there are also ways to do this via batch...
const HKEY_CURRENT_USER = &H80000001
strComputer = "."
Set StdOut = WScript.StdOut
 
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_ 
strComputer & "\root\default:StdRegProv")
 
strKeyPath = "Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles"
strValueName = "DefaultProfile"
strValue = "Backup of Outlook"
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath,strValueName,strValue

Open in new window

0
 
ThinkPaperIT ConsultantCommented:
From the sample above, the main code you would insert is lines 8-11, assuming you had your variables declared prior.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
Brent387Commented:
I didn't get a chance to try it yet, but I'm pretty sure it should work.
HKEY_CURRENT_USER = &H80000001
strComputer = "."

Set oshell = CreateObject("WScript.Shell")
Err.Clear
On Error Resume Next
strRegKey = oshell.RegRead ("HKCU\Registry Path")

If Err.Number <> 0 Then
      'If the key does not exist, then quit
      WScript.quit
Else
      'Create a registry key
    Set ObjRegistry = _
    GetObject("winmgmts:{impersonationLevel = impersonate}!\\" _
    & strComputer & "\root\default:StdRegProv")

strPath = "New\String\Path"
strValueName = "ServiceURL"
strValue = "\newkey"

objRegistry.SetStringValue _
HKEY_CURRENT_USER,strPath,StrValueName,strValue

Return = objRegistry.CreateKey(HKEY_CURRENT_USER, strPath)

If Return <> 0 Then
    WScript.Echo "The operation failed." & Err.Number
    WScript.Quit
Else
    wScript.Echo "New registry key created" & VBCRLF _
        & "HKCU\Registry Path\New\String\Path\newkey"

End If
End If

Open in new window

0
 
Brent387Commented:
Here: This is with your values in it
HKEY_CURRENT_USER = &H80000001
strComputer = "."

Set oshell = CreateObject("WScript.Shell")
Err.Clear
On Error Resume Next
strRegKey = oshell.RegRead ("HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Backup of Outlook")

If Err.Number <> 0 Then
      'If the key does not exist, then quit
      WScript.quit
Else
      'Create a registry key
    Set ObjRegistry = _
    GetObject("winmgmts:{impersonationLevel = impersonate}!\\" _
    & strComputer & "\root\default:StdRegProv")

strPath = "\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles"
strValueName = "Default Profile"
strValue = "\Backup of Outlook"

objRegistry.SetStringValue _
HKEY_CURRENT_USER,strPath,StrValueName,strValue

Return = objRegistry.CreateKey(HKEY_CURRENT_USER, strPath)

If Return <> 0 Then
    WScript.Echo "The operation failed." & Err.Number
    WScript.Quit
Else
    wScript.Echo "New registry key created" & VBCRLF _
        & "HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Backup\Default Profile""

End If
End If

Open in new window

0
 
MGS-TECHAuthor Commented:
I will try that and see if it works, Thanks a ton!
0
 
AltwiesCommented:
Here is some code that Microsoft uses as an example for Accessing the Registry using VB.Net

Imports Microsoft.Win32
Dim regVersion As RegistryKey
regVersion = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0", True)
If regVersion Is Nothing Then
    ' Key doesn't exist; create it.
    regVersion = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0")
End If
0
 
MGS-TECHAuthor Commented:
I will award the points, however I have a new question.
Alright, so a couple of things have changed. Here is my current script, instead of creating the "Backup of Outlook" profile when there is already a current Outlook profile setup on the PC, I want to ignore the rest of the script. Here is what I have so far:

' File:    outlook.vbs
' Date:    3/30/2010
'***************************************************

Option Explicit

Dim Company, PRFLocation, ProfileName



' =========================================
' ====== EDIT THIS INFORMATION=============
Company = "Company"          ' SET THE NAME OF YOUR COMPANY
PRFLocation = "\\drive\support$\outlook.prf"         ' SET THE LOCATION ON THE NETWORK OR LOCAL DRIVE
'PRFLocation = "\\drive\support$\outlook.prf" ' OF THE PRF THAT HAS BEEN CREATE
ProfileName = "Outlook"   ' This is the name that you have already
      ' created when you made the PRF.  
      ' make sure they are the same
' =========================================






' =================DO NOT EDIT ANYTHING BELOW THIS SECTION================
' ========================================================================

Set WshShell = CreateObject("WScript.Shell")
Set objNetwork = Wscript.CreateObject("Wscript.Network")
Set fso = CreateObject("Scripting.FileSystemObject")
Set ObjEnv = WshShell.Environment("Process")
Set objShell = CreateObject("Shell.Application")
Set objSysInfo = CreateObject("ADSystemInfo")
Set objUser = GetObject("LDAP://" & objSysInfo.UserName)

Const HKEY_CURRENT_USER = &H80000001
Dim HKCUfirstRunflag
HKCUfirstRunflag = "HKCU\Software\" & Company & "\FirstRunFlag"
Dim HKCUprofile
HKCUprofile = "HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\" & ProfileName

Dim WshShell, objNetwork, objEnv, fso, objShell, username, key, FirstRunCurrentUser, MSOKey, NoProfile, OfficeInstalled, strUserName, strInitials
Dim strOfficePath, strMachineName, objSysInfo, objUser
Dim objWord, LogonSrv, PRFPath, result, OSnummer, objWMIService, colOperatingSystems, objOperatingSystem

strOfficePath = "Software\Microsoft\Office\11.0\Common\UserInfo" 'Path for office user info
strMachineName = "."

' ============== START OF MAIN SCRIPT ==============
 'Check OS
' =========================================
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strMachineName & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
 result =  objOperatingSystem.Version
OSnummer = Left(result,3)

if OSnummer <> "5.1" then
 'Wscript.Echo "This is not XP"  'Debug
 Wscript.Quit  
else
 'Wscript.Echo OSnummer     'Debug
end if
Next
' =========================================
'Test to see if the script has run before
' =========================================
TestfirstRunUser  ' Has script been run before?
If FirstRunCurrentUser then 'If not then continue
 TestProfile
 If NoProfile then 'Set up profile if none exists
  OutlookSetup 'Setup Outlook profile
 End if
end if
' =========================================

' Add a registry key if the script runs successfully
WshShell.RegWrite HKCUfirstrunflag, "1", "REG_DWORD"

cleanup

' ================================================
' ============== END OF MAIN SCRIPT ==============
' ================================================

' -------- Test if first run for this user?
Sub TestFirstRunUser
  on error resume next 'cannot be read first time
  key = WshShell.RegRead(HKCUfirstRunflag)
  If Err <> 0 Then
    FirstRunCurrentUser = True
  Else
    FirstRunCurrentUser = False
  End If
  On Error Goto 0
End Sub


'------------ Test if profile exists?
Sub TestProfile
 on error resume next 'cannot be read first time
 MSOKey = WshShell.RegRead(HKCUprofile)
' determine if a profile has already been setup
  If MSOKey = "" Then
   'wscript.echo "No Profile" 'Testing
   NoProfile = True
  else
   'wscript.echo "Profile exists" 'Testing
   NoProfile = False
  end if
  On Error Goto 0
End sub

Sub OutlookSetup
    WshShell.Run "outlook.exe /importprf " & PRFLocation, 1, False
End Sub

Sub Cleanup
 Set objNetwork = Nothing
 Set objSysInfo = Nothing
 Set WshShell = Nothing
 Set fso = Nothing
 Set ObjEnv = Nothing
 Set objShell = Nothing
 Set objUser = Nothing
 Set objWord = Nothing
 Set objWMIService = Nothing
 Set colOperatingSystems = Nothing
 Set objWord = Nothing
End Sub
0
 
Brent387Commented:
If the variables are the same, you don't need to define them twice. I'm not sure that I am understanding your question completely. I add the "str" just to keep it straight in my head haha. You'll want to:
Dim Company, PRFLocation, strPRFLocation
strCompany = "Company Name"
strPRFLocation = "\\drive\support$\outlook.prf"  
strProfileName = "Outlook"

' You seem to have a good grip on this but just a reminder, at the end:
strCompany = Nothing
strPRFLocation = Nothing
strProfileName = Nothing
0
 
MGS-TECHAuthor Commented:
Brent,
To clarify, Here is what I would like my script to do:
When a new user logs in to the PC for the first time, it will create the Outlook profile based on the information in the Outlook.prf file.
This works fine. However, when an existing user that has already logged into the PC and already has an Outlook profile setup, I would like to ignore the new profile creation and leave the existing Outlook profile intact.  I would do this by checking the registry key

[HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles]

If there is already a Outlook key setup, than ignore the rest of the script.

Does that make any sense?

Thanks for the help, it's much appreciated.
0
 
Brent387Commented:
strRegKey = oshell.RegRead ("HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Backup of Outlook")
 
If Err.Number <> 0 Then
      'If the key does not exist, then quit
      WScript.quit
Else


This is in the original code I posted.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 4
  • 3
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now