Alex Hope O'Connor
Alex Hope O'Connor

Reputation: 9694

Batch file read from largest registry sub-key?

I am trying to modify my batch script to get the install path for a piece of software, however it needs to be version independent and the install path is stored in a version sub-key, so basically what I am looking to do is detect the greatest version sub-key and get the install path from there.

Here is what the code for getting the registry value looks like now:

FOR /F "skip=2 tokens=2,*" %%A IN ('REG.exe query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node......\6.30" /v "InstallLocation"') DO set "InstallPath=%%B"

Basically I want to not be dependent on the "6.30" part on the end of the key address, how can I do this?

Upvotes: 0

Views: 831

Answers (1)

David Ruhmann
David Ruhmann

Reputation: 11367

Since I do not know which exact software you are looking at, I will reference Adobe Reader on Winodws 7 x64.

Answer:

The following example will output all of the sub keys within the parent.

for /f "delims=" %%A in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Adobe\Acrobat Reader"') do if not "%%~A"=="" echo.%%~nxA

Output:

9.5
10.0
11.0

Sample:

From there it would just be a matter of remembering the largest and using it in the next query for the value data.

@echo off
setlocal EnableDelayedExpansion
set "xVersion="
set "xPath="

:: Retrieve Greatest Version
for /f "delims=" %%A in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Adobe\Acrobat Reader"') do (
    if not "%%~A"=="" if "%%~nxA" GTR "!xVersion!" set "xVersion=%%~nxA"
)

:: Validate Version
if "%xVersion%"=="" goto :eof

:: Retrieve Install Path
for /f "tokens=1,2,*" %%A in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Adobe\Acrobat Reader\%xVersion%\Installer" /v Path') do (
    set "xPath=%%~C"
)

:: Show Results
echo.%xPath%
endlocal

Output:

C:\Program Files (x86)\Adobe\Reader 10.0\

Bonus:

If you want to validate that the %%~nxA is a number, here is a batch routine of mine.

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:IsNumber <xReturn> <xInput> [xDelims]
:: Return true if the input is a base 10 number, else return false.
:::: Does not allow any seperators unless specified by xDelims. ,.[tab][space]
setlocal
if not "%~2"=="" set "xResult=true"
for /f "tokens=1 delims=1234567890%~3" %%n in ("%~2") do set xResult=false
endlocal & if not "%~1"=="" set "%~1=%xResult%"
goto :eof

:: Usage Example.
:: The variable xResult will be set to true if %%~nxA is a decimal number.
call :IsNumber xResult "%%~nxA" "."

Upvotes: 1

Related Questions