如何将值从一个批处理文件返回到调用者批处理文件

时间:2013-07-19 15:58:23

标签: batch-file command-line-arguments

我有一个常见的.bat文件,它读取status.xml文件并找出状态字段的值。然后,其他批处理文件调用此批处理文件以查找状态值。调用批处理文件将文件名发送到公共bat文件。 我无法将状态从公共批处理文件发送到调用批处理文件。 有人可以帮忙吗?

main batch file
-- will call the common bat file and send the file name and a variable as arguments
setlocal
call Common.bat c:\folderdir\files\status.xml val1
-- trying to print the status returned by the common bat file
echo [%val1%]

common batch file
@ECHO off
setlocal EnableDelayedExpansion

rem will loop through the file and read the value of the status tag
(for /F "delims=" %%a in (%1) do (
set "line=%%a"
set "newLine=!line:<Interface_status>=!"
set "newLine=!newLine:</Interface_status>=!"
if "!newLine!" neq "!line!" (
  @echo Status is !newLine!
rem I want to send`enter code here` the value of newLine to the calling batch file
  set %~2 = !newLine!   <--this does not work
)

)) 

2 个答案:

答案 0 :(得分:4)

在SETLOCAL / ENDLOCAL括号内(其中EOF = ENDLOCAL)将撤消对环境所做的任何更改。

您需要在Common.bat内设置一个在最后的闭括号后可见的变量(即您的返回值 - 它可能是一个空字符串。

然后,在common.bat的最后一个括号之后的行中,放上这一行:

ENDLOCAL&set %~2=%returnvalue%

其中returnvalue包含呃,你希望返回的值(有趣,那......)

BTW:字符串SET是SPACE-SENSITIVE。如果该行有效,您将设置变量"VAR1 " - 而不是"VAR1" - 变量名中=包含的空格 - 以及{{之后的任何空格1}}同样包含在分配的值中。

语法

=

通常用于排除某一行上的任何杂散尾随空格(某些编辑可能会留下)


(叹气)...

set "var=value"

答案 1 :(得分:2)

Peter Wright描述了主要技巧。

最后一个问题似乎是退出for循环而不会丢失值。

您可以使用GOTO :break作为GOTO立即停止所有循环。

无法在!newline!块中使用ENDLOCAL,因为这会在ENDLOCAL之后展开,但随后会变空。

@ECHO off
setlocal EnableDelayedExpansion

for /F "delims=" %%a in (%1) do (
  set "line=%%a"
  set "newLine=!line:<Interface_status>=!"
  set "newLine=!newLine:</Interface_status>=!"
  if "!newLine!" neq "!line!" (
    @echo Status is !newLine!
    goto :break
  )
)

( 
  endlocal
  set "%~2=%newLine%"
)

如果你在newLine中的值可能包含引号,那么最好使用一种更安全的技术:

for /F "delims=" %%a in ("!newline!") DO (
  endlocal
  set "%~2=%%~a" 
)
相关问题