8

I am trying to get the Data from a registry key value via command line

I can retrieve the value of a registry key using the following code

reg query HKCU\Software\[PATH_TO_MY_DIR] /v [KEY_NAME]

This works as expected and outputs three items:

  • Name
  • Type
  • Data

I am trying to get the data from the value in command line how do I do this?

Demodave
  • 6,242
  • 6
  • 43
  • 58

1 Answers1

6

This can be done very simply using a FOR loop along-side it's Token System. Since reg query will output the variables in a one two three format, we can use tokens=3 to grab only the third item in the output.

From CMD:

for /F "tokens=3" %A in ('reg query "HKCU\Software\[PATH_TO_MY_DIR]" /v "[KEY_NAME]"') DO (Echo %A)

From BATCH:

for /F "tokens=3" %%A in ('reg query "HKCU\Software\[PATH_TO_MY_DIR]" /v "[KEY_NAME]"') DO (Echo %%A)
John Kens
  • 1,615
  • 2
  • 10
  • 28
  • 6
    This won't work if the registry value contains spaces. – Stevoisiak Aug 08 '19 at 20:04
  • changing token to =3,* and adding %B in echo will take care of spaces for the last field. But you will have to change(add) the token if there is space in the keyname. – Zunair Mar 30 '20 at 08:21
  • 1
    Also, `reg query` outputs a blank line followed by a header listing the key path before the 'value/type/data' line. If this header contains 2 (or more) spaces (probably in the [PATH_TO_MY_DIR] or that with a subkey name) then it will produce spurious output. So should be `for /f "skip=2 tokens=...` (note: even though a blank line is ignored when tokenizing, it must be included in the skip count) – Uber Kluger Sep 15 '20 at 20:21
  • It's worked for me with spaces, thanks Zunair. : for /F "tokens=3*" %A in ('reg query "HKCU\SOFTWARE\Valve\Steam" /v "SteamExe"') DO (Echo %A %B) – Hasan Merkit Apr 14 '21 at 11:28
  • using `FOR /F "tokens=2*" %%A IN ('reg query ...') DO echo %%~B` If registry value is a string then `%%A` will have `REG_SZ` and the remainder will be pure in `%%B` – NiKiZe Jun 16 '21 at 07:59