Search code examples
batch-fileregistry

If reg key and value exist in batch


How can I check if reg key and value exist in a batch file and change the value if it exists. Below is what I'm trying to do in English.

HKCU\Software\App

IF "Directory" = "c:\users\%username%\AppData" THEN change to "Directory" = "%userprofile%\AppData" ELSE do nothing


Solution

  • See whether this works:

    @echo off & setlocal
    
    reg query HKCU\Software\App /v Directory 2>NUL || (
        reg add HKCU\Software\App /v Directory /t REG_EXPAND_SZ /d "%%userprofile%%\AppData"
    )
    

    See reg query /? and reg add /? in a cmd console for full details of syntax.


    Edit: Restricting the creation of the reg value only if it exists and contains a specific location requires a bit more logic. If the path contained in the registry contains a trailing backslash, or an inline dot, or has %username% expanded or not expanded, this can cause a simple string match to fail. When comparing paths, it's a good idea to cd or pushd into the directory to ensure it's in a unified format, all relative directories are resolved, all variables expanded, trailing slash is stripped, etc. Comparing the short filenames by using a for loop + %%~sI or similar is another option, but the pushd method has an added benefit of testing whether the directory exists and can be accessed.

    @echo off & setlocal
    
    rem // proceed only if the App key exists in the registry
    reg query HKCU\Software\App >NUL 2>NUL && (
    
        for /f "skip=2 tokens=2*" %%I in (
            'reg query HKCU\Software\App /v Directory 2^>NUL'
        ) do call pushd "%%~J" 2>NUL && (
            rem // call pushd "%%~J" ensures the dir exists and the location is normalized
    
            setlocal enabledelayedexpansion
            if /i "!CD!"=="C:\Users\%username%\AppData" call :regupdate
            endlocal
    
            popd
    
        rem // if pushd failed, the path is invalid.  Update it.
        ) || call :regupdate
    )
    
    exit /b
    
    :regupdate
    reg add HKCU\Software\App /v Directory /t REG_EXPAND_SZ /d "%%userprofile%%\AppData" /f
    

    One other note: %appdata% and %localappdata% might be preferable to %userprofile%\AppData depending what you intend to do with the value once retrieved. See this page for a full list of Windows environment variables.