我启动一个批处理文件来处理一些代码,一次它调用另一个批处理文件并且应该返回一个变量,但是手册页中解释的关于 local/endlocal 的方法似乎在这里不起作用,请问我做错了什么?
第一个批处理文件:
@ECHO OFF
setlocal
call secondbatchfile.bat xyz
echo. [%val1%]
第二个批处理文件:
@if (@a==@b) @end /* <== btw what does this code do ???
@echo off
setlocal enabledelayedexpansion
set "URL=%~1"
set bla bla ...
do bla bla ...
for /f "delims=" %%I in ('cscript /nologo /e:jscript "%~f0" "%URL%"') do (
rem trim whitespace from beginning and end of line
for /f "tokens=*" %%x in ("%%~I") do set "line=%%x"
rem test that trimmed line matches "variable=number"
echo !line! | findstr /i "^to[a-z]*=[0-9]*" >NUL && (
rem test was successful. Scrape number.
for /f "tokens=2 delims==" %%x in ("%%I") do set "val1=%%x"
echo !val1! <== this works
ENDLOCAL & SET top=%val1% <== this not
)
)
这导致:
c:\test>firstbatchfile.bat
123456789 <== this works
[] <== this not
我尝试了不同的 return var 语法,例如!val1!
or %%val1
- 没有奏效。我错过了什么?
更新: 关于网站上的其他示例,我尝试过:
call seconbatchfile.bat xyz ret1
echo. [%2%] [%ret1%]
并在第二个文件更改:
rem ENDLOCAL & SET %2=!val1!
也不行吗?
解决方案:
第二个批处理文件可以是来自 rojo 读取整个网站的原始脚本,我确实保留了修剪和匹配语法行以仅返回相关匹配:
for /f "delims=" %%I in ('cscript /nologo /e:jscript "%~f0" "%URL%"') do (
rem trim whitespace from beginning and end of line
for /f "tokens=*" %%x in ("%%~I") do set "line=%%x"
rem test that trimmed line matches "variable=number"
echo !line! | findstr /i "^[a-z]*=[0-9]*" >NUL && (
echo(%%I
)
)
第一个调用它的批处理文件将搜索两个所需的参数,如下所示:
@ECHO OFF
setlocal
for /f "delims=" %%I in ('secondbatchfile.bat "http://xyz"') do (
echo %%I | findstr /i "top" >NUL && (
for /f "tokens=2 delims==" %%x in ("%%I") do (
set "updir=%%x"
)
)
echo %%I | findstr /i "low" >NUL && (
for /f "tokens=2 delims==" %%x in ("%%I") do (
set "lowdir=%%x"
)
)
)
echo.[%updir%]
echo.[%lowdir%]
非常感谢 rojo 的精彩代码