批量注册查询键变量

Batch reg query key to variable

当我在 cmd 上 运行 命令 REG Query HKLM /k /F "Command Processor" /s /e /c 时,我得到了这个结果:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Command Processor

最终结果:找到 2 个匹配项。

但批量:

@echo off & setlocal ENABLEEXTENSIONS
for /f "tokens=*" %%a in ('REG Query HKLM /k /F "Command Processor" /s /e /c') do set "MyPath=%%a"
echo The path string value is "%MyPath%"
pause

当我执行这个时,我只得到最后一行:

路径字符串值为"End results: 2 match(s) found(s)."

怎么了?我想获取变量的路径键。

问题很明显:您在 for /F 循环中覆盖 MyPath 的值,然后打印 (echo) final value/line.

要获得 所有 行(任意数字),您可以执行以下操作:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
rem storing the path strings in `MyPath1`, `MyPath2`, etc.:
set /A count=0
for /F "delims=" %%A in (
    'REG Query HKLM /K /F "Command Processor" /S /E /C ^
    ^| findstr /L /B /V /C:"End of search: "'
) do (
    set /A count+=1
    set "MyPath!count!=%%A"
)
rem extracting the previously stored path strings:
echo Total number of path strings: %count%
for /L %%B in (1,1,%count%) do (
    echo The !count!. path string value is "!MyPath%%B!"
)
pause
endlocal

这构成了一个数组MaPath1MyPath2等的排序,包含了所有匹配的路径字符串。

findstr命令用于过滤摘要行End of search:(这可能会根据您的系统进行调整locale/language)。

请注意,在 endlocal 命令后该数组不再可用。