从批处理脚本中读取文本文件时,无法获取已存在的值。
版
8.0.56336(版本和值之间没有空格)
@echo off
setlocal EnableDelayedExpansion
set num=0
if %errorlevel%==0 (
FOR /F "tokens=* delims=" %%a IN ('"wmic product where "Name like 'Microsoft Visual C++ 2005 Redistributable'" get version"') do (
echo %%%a >> doxygen.txt
)
rem FOR /F "tokens=* delims=" %%x in (doxygen.txt) DO echo %%x
for /f "tokens=* delims=" %%i in (doxygen.txt) do (
set /a num+=1
set v[!num!]=%%i
)
del doxygen.txt
set line1=%v[1]%
set line2=%v[2]%
set line3=%v[3]%
set line4=%v[4]%
echo line1: %line1%
echo line2: %line2%
echo line3: %line3%
echo line4: %line4%
endlocal
)
)
此处无法获取line1,line2等的值。
任何人都可以建议我在哪里犯了错误。
提前致谢。
答案 0 :(得分:1)
在执行行或括号块之前,批量展开百分比表达式 因此设置line1 =%v [1]%将简单地扩展为空,因为它在FOR循环开始之前展开。
但您可以使用延迟扩展语法,因为这些语法在运行时中展开。
@echo off
setlocal EnableDelayedExpansion
set num=0
if %errorlevel%==0 (
FOR /F "tokens=* delims=" %%a IN ('"wmic product where "Name like 'Microsoft Visual C++ 2005 Redistributable'" get version"') do (
echo %%a>> doxygen.txt
)
rem FOR /F "tokens=* delims=" %%x in (doxygen.txt) DO echo %%x
for /f "tokens=* delims=" %%i in (doxygen.txt) do (
set /a num+=1
set "v[!num!]=%%i"
)
del doxygen.txt
set "line1=!v[1]!"
set "line2=!v[2]!"
set "line3=!v[3]!"
set "line4=!v[4]!"
echo line1: !line1!
echo line2: !line2!
echo line3: !line3!
echo line4: !line4!
)
endlocal
答案 1 :(得分:0)
如果您只是想从输出中获取版本,这是一种更简单的方法:
<强> 1 强>
@echo off
setlocal EnableDelayedExpansion
set num=0
if %errorlevel%==0 (
FOR /F "skip=1 tokens=* delims=" %%v IN ('wmic product where "Name like 'Microsoft Visual C++ 2005 Redistributable'" get version ^| findstr "."') do (
echo Version: %%v
set mc_vcpp_05=%%v
)
)
endlocal
2:
如果您因某些原因需要阅读该文件,请执行以下操作:
@echo off
if %errorlevel%==0 (
FOR /F "skip=1 tokens=1 delims= " %%a IN ('wmic product where "Name like 'Microsoft Visual C++ 2005 Redistributable'" get version ^| findstr "."') do (
echo %%a >> doxygen.txt
)
for /f "tokens=1* delims=" %%I in ('type doxygen.txt') do (
echo Version: %%I
)
del doxygen.txt
)
为什么它在你的原始剧本中表现得很好,我还不知道。当我发现
时,我会编辑或评论我的答案