Scripting: Fetch Registry Values for Fun and ProfitSince Microsoft Windows XP, reg.exe has been the in-box method to retrieve/set registry values. While it is relatively simple to parse values from a reg query command, it presents some challenges in longer or complex scripts where a consistent mechanism for retrieving registry values may be desirable. For example, consider the following command:
The output of this command is: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders Personal REG_SZ C:\Users\User\Documents Although the output contains a leading blank line, a header and a trailing blank line, this is easy to parse to extract the required value:
C:\Users\User\Documents However, consider if the variable name being requested contains spaces:
outputs: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders My Music REG_SZ C:\Users\User\Music In this case the required value is the fourth token (1-3,*) of the output instead of the third (1-2,*). This makes the prospect of a generic approach to retrieving registry values complex. Additionally, if the value is a REG_DWORD, reg.exe returns the hexadecimal representation of the value and for scripting purposes this usually needs converting to decimal (with set /A).
HKEY_CURRENT_USER\Console PowerShell contains a method Get-ItemProperty which can solve these issues:
outputs:
(The purpose of preloading the required key name into $value is to make it easier to process the results from Get-ItemProperty if it contains spaces.) This syntax could be formed into a subroutine within a script as follows:
for /f "usebackq tokens=*" %%x in (`PowerShell "$value='%~3';(Get-ItemProperty -Path 'Registry::%~2' -Name $value).$value"`) do set %~1=%%x goto :EOF or alternatively:
for /f "usebackq tokens=*" %%x in (`PowerShell "(Get-Item 'Registry::%~2').GetValue('%~3')"`) do set %~1=%%x goto :EOF To use the routine:
echo %Result% call :RegQuery Result "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" "My Music" call :RegQuery Result HKCU\Console ScreenBufferSize Output:
C:\Users\User\Music 1638480 Copyright © 1996-2023 Cadzow TECH Pty. Ltd. All rights reserved. Information and prices contained in this website may change without notice. Terms of use. Question/comment about this page? Please email webguru@cadzow.com.au |