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

use*_*173 14 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
)

)) 
Run Code Online (Sandbox Code Playgroud)

Mag*_*goo 5

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

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

然后,在common.bat's 最后一个右括号之后的行中,放置以下行:

ENDLOCAL&set %~2=%returnvalue%
Run Code Online (Sandbox Code Playgroud)

wherereturnvalue包含您希望返回的 er, 值(有趣,那个...)

顺便说一句:字符串SET是空间敏感的。如果该行有效,您将设置变量"VAR1 "- 而不是"VAR1"- 之前的空格=将包含在变量名称中 - 以及=同样包含在分配的值中的任何空格。

语法

set "var=value"
Run Code Online (Sandbox Code Playgroud)

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


(叹)...

@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 SET THE RETURN VALUE
  set RETURNVALUE=!newLine!
)

)) 

ENDLOCAL&SET %~2=%RETURNVALUE%
Run Code Online (Sandbox Code Playgroud)