Search code examples
batch-fileregistry

Batch File: If registry key's data equals x


I'm trying to check whether a recording device is enabled or disabled. I've tried a ton of examples I've found, but just can't get it to work. Both of the commands I use to change the data work.

Here's what I currently have:

REG QUERY "Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture\{f2b4b04b-e32f-494a-94fc-f7846a7fc275}" /v 

"DeviceState" | Find "1"
IF %ERRORLEVEL% == 1 goto turnoff
If %ERRORLEVEL% == 0 goto turnon
goto end

:turnon
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture\{f2b4b04b-e32f-494a-94fc-f7846a7fc275}" /v DeviceState /d 1 /t Reg_DWord /f


:turnoff
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture\{f2b4b04b-e32f-494a-94fc-f7846a7fc275}" /v DeviceState /d 0x10000001 /t Reg_DWord /f
goto end

:end
@exit

I'm not sure if the Find "1" should actually be 1. When I query that data and the device is enabled, the output is DeviceState REG_DWORD 0x1 and while the device is disabled, the output is DeviceState REG_DWORD 0x10000001


Solution

  • set key=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion^
    \MMDevices\Audio\Capture\{f2b4b04b-e32f-494a-94fc-f7846a7fc275}
    
    reg query "%key%" /v DeviceState | find "0x10000001"
    if errorlevel 1 goto turnoff
    goto turnon
    
    :turnon
    reg add "%key%" /v DeviceState /d 0x1 /t REG_DWORD /f
    goto :eof
    
    :turnoff
    reg add "%key%" /v DeviceState /d 0x10000001 /t REG_DWORD /f
    goto :eof
    

    Or shorter code without using goto:

    set key=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion^
    \MMDevices\Audio\Capture\{f2b4b04b-e32f-494a-94fc-f7846a7fc275}
    
    reg query "%key%" /v DeviceState | find "0x10000001"
    if errorlevel 1 (set "data=0x10000001") else set "data=0x1"
    reg add "%key%" /v DeviceState /d %data% /t REG_DWORD /f
    

    The use of ^ at end of line is a line continuation character i.e. the interpreter removes the ^ and joins the next line to the current line.

    HKEY_LOCAL_MACHINE can be substituted with HKLM in the reg commands.

    goto :eof a.k.a goto end of file will end the script.

    Issues in your code:

    • Commands after :turnon label continue on to the :turnoff label commands thus :turnon commands are undone.

    • find "1". 1 can be found in 0x1 and in 0x10000001. Advise find "0x10000001" as it is unique to both data values.

    Note:

    I tested with HKLM\SOFTWARE\~Microsoft\... key instead of HKLM\SOFTWARE\Microsoft\... key as on Win7, the key of MMDevices and subkeys has SYSTEM permissions set and admin and user groups do not have permission to write.