batch-filecmd

Delete Registry Key if empty (One line code)


I'm trying to do a one line batch command that would delete a Key if it's empty. Below are 2 solutions that should work be for some strange reason they don't. 😩

For /f "tokens=*" %%a in ('Reg Query "HKCU\Software\RandomKey" 2^>NUL ^| FindStr /l /i /c:"\\Software\\RandomKey\\"') do (EXIT) ^& Reg Delete "HKCU\Software\RandomKey" /f 1>NUL

For /f "tokens=*" %%a in ('Reg Query "HKCU\Software\RandomKey" 2^>NUL ^| FindStr /l /i /c:"\\Software\\RandomKey\\"') do Set "FSK=1" ^& If Not "%FSK%"=="1" Reg Delete "HKCU\Software\RandomKey" /f 1>NUL

Solution

  • Here's a test:

    @ECHO OFF
    SETLOCAL
    
    FOR %%y IN ("RandomKey" "GIGABYTE" "Notepad++" "7-zip") DO (
     ECHO testing "%%~y"
     rem show Reg Query output for demonstration
     Reg Query "HKEY_LOCAL_MACHINE\SOFTWARE\%%~y" 2>&1
     Reg Query "HKEY_LOCAL_MACHINE\SOFTWARE\%%~y" 2>&1|FINDSTR /b /c:"    (Default)">nul&IF NOT ERRORLEVEL 1 ECHO DO whatever
     echo/
    ) 
    GOTO :EOF
    

    On my system:

    "RandomKey" Doesn't exist; error message redirected to stdout to avoid clutter
    
    "GIGABYTE" Exists, but is not empty (has subkeys)
    
    "Notepad++" Is empty and generates the message
    
    "7-zip" is not empty.
    

    The findstr command looks for the /c: constant string between quotes (note 4 leading spaces & case-sensitive) at /b the beginning of the line.

    Results on my machine

    testing "RandomKey"
    ERROR: The system was unable to find the specified registry key or value.
    
    testing "GIGABYTE"
    
    HKEY_LOCAL_MACHINE\SOFTWARE\GIGABYTE\Control Center
    HKEY_LOCAL_MACHINE\SOFTWARE\GIGABYTE\DramInfos
    HKEY_LOCAL_MACHINE\SOFTWARE\GIGABYTE\GBT_GCC_Lib
    
    testing "Notepad++"
    
    HKEY_LOCAL_MACHINE\SOFTWARE\Notepad++
        (Default)    REG_SZ    C:\Program Files\Notepad++
    
    DO whatever
    
    testing "7-zip"
    
    HKEY_LOCAL_MACHINE\SOFTWARE\7-zip
        Path64    REG_SZ    C:\Program Files\7-Zip\
        Path    REG_SZ    C:\Program Files\7-Zip\