How can I get the value of a registry key from within a batch script?

前端 未结 17 2471
抹茶落季
抹茶落季 2020-11-27 15:12

I need to use a REG QUERY command to view the value of a key and set the result into a variable with this command:

FOR /F \"tokens=2* delims=    \" %%A IN (\         


        
相关标签:
17条回答
  • 2020-11-27 15:30
    @echo off
    setlocal ENABLEEXTENSIONS
    set KEY_NAME=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\awhost32.exe
    set VALUE_NAME=Path
    for /F "usebackq tokens=3" %%A IN (`reg query "%KEY_NAME%" /v "%VALUE_NAME%" 2^>nul ^| find "%VALUE_NAME%"`) do (
      echo %%A
    )
    

    How do you handle a space in the %%A variable? This results in C:\Program. The actual path is C:\Program Files\Symantec\pcAnywhere.

    0 讨论(0)
  • 2020-11-27 15:33

    With regedit:

    @echo off
    setlocal
    ::if the scrit is not ran as administrator
    ::  and the key does not require admin permissions
    set __COMPAT_LAYER=RunAsInvoker
    
    set "key=%~1"
    set "value=%~2"
    
    regedit /e "#.reg" "%key%"
    
    
    for /f "tokens=1,* delims==" %%a in ('find  """%value%""=" "#.reg"') do if "%%~b" neq "" echo %%~b
    del /q #.reg
    
    endlocal
    

    Example:

    call regreader.bat "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0\Setup\1033\" Version
    

    output:

    3.0.30729.4926

    0 讨论(0)
  • 2020-11-27 15:36

    Great level of solutions here.

    My little grain of salt as the solution @Patrick Cuff did not work out of the box; I had 2 problems

    • I use Windows 7 => changed to "skip=2"
    • The value of the registry value had a space in it Value Value = C:\Program Files\...

    Here is the solution I found: taking 4 tokens and setting ValueValue to %%C and %%D. (Thanks @Ivan!)

    setlocal ENABLEEXTENSIONS
    set KEY_NAME="HKEY_CURRENT_USER\Software\Microsoft\Command Processor"
    set VALUE_NAME=DefaultColor
    
    FOR /F "usebackq skip=2 tokens=1-4" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
        set ValueName=%%A
        set ValueType=%%B
        set ValueValue=%%C %%D
    )
    
    if defined ValueName (
        @echo Value Name = %ValueName%
        @echo Value Type = %ValueType%
        @echo Value Value = %ValueValue%
    ) else (
        @echo "%KEY_NAME:"=%\%VALUE_NAME%" not found.
    )
    
    0 讨论(0)
  • 2020-11-27 15:39
    set regVar_LocalPrjPath="LocalPrjPath"
    set regVar_Path="HKEY_CURRENT_USER\Software\xyz\KeyPath"
    
    :: ### Retrieve VAR1 ###
    FOR /F "skip=2 tokens=2,*" %%A IN ('reg.exe query %regVar_Path% /v %regVar_LocalPrjPath%') DO set "VAR1=%%B"
    
    0 讨论(0)
  • 2020-11-27 15:42

    Thanks, i just need to use:

    SETLOCAL EnableExtensions
    

    And put a:

    2^>nul
    

    Into the REG QUERY called in the FOR command. Thanks a lot again! :)

    0 讨论(0)
提交回复
热议问题