读取由空格和空格分隔的单词字符串值还包含批处理脚本中的空格

时间:2016-09-09 09:42:29

标签: batch-file

我需要从批处理脚本中读取注册表的默认值。某些项目的名称包含一些空格。另外,我想在批处理文件中执行for循环两次。

rem @echo OFF

setlocal ENABLEEXTENSIONS
set KEY_NAME="HKEY_CURRENT_USER\Software\abc\xyz pqr"

FOR /F "tokens=1-3 delims=<TAB>" %%A IN ('REG QUERY %KEY_NAME% 2^>nul') DO (
    set ValueName=%%A
    set ValueType=%%B
    set ValueValue=%%C
)
if defined ValueName (
    @echo Value Name = %ValueName%
    @echo Value Type = %ValueType%
    @echo Value Value = %ValueValue%
) else (
    @echo %KEY_NAME%\%VALUE_NAME% not found.
)
pause

它提供以下输出

rem @echo OFF

setlocal ENABLEEXTENSIONS

set KEY_NAME="HKEY_CURRENT_USER\Software\abc\xyz pqr"

FOR /F "tokens=1-3 delims=<TAB>" %A IN ('REG QUERY "HKEY_CURRENT_USER\Software\abc\xyz pqr" 2>nul') DO (
set ValueName=%A
 set ValueType=%B
 set ValueValue=%C
)

(
set ValueName=HKEY_CURREN
 set ValueType=_USER\Software\abc\xyz pq
 set ValueValue=
)

(
set ValueName=    (Default)    REG_SZ    C:\Program Files (x86)\abc\
 set ValueType=
 set ValueValue=
)

(
set ValueName=
 set ValueType=uthor    REG_SZ    gj
 set ValueValue=
)

(
set ValueName=    Version    REG_SZ    1.4.0.0
 set ValueType=
 set ValueValue=
)

if defined ValueName (



)  else ()
Value Name =     Version    REG_SZ    1.4.0.0
Value Type =
Value Value =

pause
Press any key to continue . . .

我想获得以下输出,并且还希望一旦获得(默认值)

的值,这个for循环应该停止
(
set ValueName=(Default)
set ValueType=REG_SZ
set ValueValue=C:\Program Files (x86)\abc\
)

先谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

此注释的批处理代码应适用于Windows XP及更高版本的Windows版本。

@echo off
rem On Windows Vista and later REG.EXE outputs without version info:

rem HKEY_CURRENT_USER\Software\abc\xyz pqr
rem    (Default)    REG_SZ    C:\Program Files (x86)\abc\

rem There are only spaces used to separate value name, value type and value string.


rem But REG.EXE version 3.0 outputs on Windows XP with version info:

rem ! REG.EXE VERSION 3.0
rem
rem HKEY_CURRENT_USER\Software\abc\xyz pqr
rem     <NO NAME>   REG_SZ  C:\Program Files (x86)\abc\

rem NOTE: There are 4 indent spaces and 2 separating tabs in REG 3.0 output line.


rem So either token 2 or token 3 contains value type REG_SZ
rem used to identify the line with the wanted information.
set "TypeToken=2"

:GetPathFromRegistry
for /F "skip=1 tokens=%TypeToken%*" %%A in ('%SystemRoot%\System32\reg.exe QUERY "HKCU\Software\abc\xyz pqr" /ve 2^>nul') do (
    if "%%A" == "REG_SZ" (
        set "AppPath=%%~B"
        goto HaveAppPath
    ) else if "%%A" == "NAME>" (
        set "TypeToken=3"
        goto GetPathFromRegistry
    )
)

echo Failed to read application path from registry.
pause
goto :EOF

:HaveAppPath
echo Application path is: %AppPath%
pause

在Windows VISTA及更高版本的Windows版本中, FOR 循环仅处理来自 REG 输出的1行。

在Windows XP和Windows Server 2003上, FOR 循环使用tokens=X*的不同值运行两次,并在获取感兴趣的字符串值之前处理更多行,因为版本信息输出按reg.exe版本3.0。

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • echo /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • reg /?
  • reg query /?
  • set /?