17

I have a common .bat file that reads the status.xml file and finds out the value of the status field. This batch file is then called by other batch files for finding out status value. the calling batch files send the file name to the common bat file. I am not able to send the status from the common batch file to the calling batch files. Can someone please help?

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
)

)) 
4

2 回答 2

5

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

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

然后,在common.bat最后的右括号之后的行中,放入以下行:

ENDLOCAL&set %~2=%returnvalue%

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

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

语法

set "var=value"

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


(叹)...

@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%
于 2013-07-19T16:27:41.550 回答
3

Peter Wright 描述了主要技术。

最后一个问题似乎是在不丢失值的情况下退出 for 循环。

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

不能!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" 
)
于 2013-07-19T17:01:35.947 回答