28

我正在寻找一种使用 Windows 批处理文件的方法,该文件调用传递 1-9 个参数和返回值(字符串)的子批处理文件,而无需将返回值保存到文件/等中。我将返回值保存到变量中,就像在 @FOR /F 中所做的那样

我看着

@FOR /F "tokens=*" %%i IN ('%find_OS_version%') DO SET OS_VER=%%i

Call function/batch %arg1% %arg2%

我没有看到如何设置来执行此操作

编辑:dbenham 有点回答我的问题。他的例子是在批处理文件主要部分和功能之间。我的问题是在两个不同的批处理文件之间。以 dbenham 为基础的答案是以下布局。

主批处理文件

CALL sub_batch_file.bat  return_here "Second parameter input"

REM echo is Second parameter input
ECHO %return_here%
REM End of main-batch file

sub_batch_file.bat

@ECHO OFF
SETLOCAL

REM ~ removes the " "
SET input=%~2
(
    ENDLOCAL
    SET %1=%input%
)
exit /b
REM End of sub-batch file
4

3 回答 3

50

通常批处理函数以两种方式之一返回值:

EXIT /B n1) 使用where n = some number可以通过错误级别返回单个整数值。

@echo off
setlocal
call :sum 1 2
echo the answer is %errorlevel%
exit /b

:sum
setlocal
set /a "rtn=%1 + %2"
exit /b %rtn%

2)更灵活的方法是使用环境变量返回一个或多个值

@echo off
setlocal
call :test 1 2
echo The sum %sum% is %type%
call :test 1 3
echo The sum %sum% is %type%
exit /b

:test
set /a "sum=%1 + %2, type=sum %% 2"
if %type%==0 (set "type=even") else (set "type=odd")
exit /b

存储答案的变量名可以作为参数传入!并且中间值可以从主程序中隐藏。

@echo off
setlocal
call :test 1 2 sum1 type1
call :test 1 3 sum2 type2
echo 1st sum %sum1% is %type1%
echo 2nd sum %sum2% is %type2%
exit /b

:test
setlocal
set /a "sum=%1 + %2, type=sum %% 2"
if %type%==0 (set "type=even") else (set "type=odd")
( endlocal
  set "%3=%sum%"
  set "%4=%type%"
)
exit /b

有关最后一个示例如何工作的完整说明,请阅读 DOStips 上的这个出色的批处理函数教程

更新

以上对于可以返回的内容还是有限制的。有关支持更广泛值的基于 FOR 的替代方法,请参阅https://stackoverflow.com/a/8254331/1012053 。请参阅https://stackoverflow.com/a/8257951/1012053,了解一种“神奇”技术,在任何情况下都可以安全地返回绝对长度 < ~8190 的任何值。

于 2012-07-14T18:09:18.847 回答
5

提示

Setlocal EnableDelayedExpansion
IF 1==1 (
    CALL :LABEL
    echo 1: %errorlevel%
    echo 2: !errorlevel!
)
echo 3: %errorlevel%

:LABEL
EXIT /B 5

输出将是:

1: 0
2: 5
3: 5

EnableDelayedExpansion允许您使用!var_name!在执行时扩展 var,而不是解析时。

于 2014-08-11T17:30:08.360 回答
1

你错过了几件事:

  • 使用反引号而不是单引号。
  • 使用 tokens 命令在双引号内添加 usebackq。

这个字符`不是这个字符'

在美式英语键盘上,反引号是 shift-tilde,通常位于数字行中 1 的左侧。

@FOR /F "usebackq tokens=*" %%i IN (`%find_OS_version%`) DO SET OS_VER=%%i
于 2012-07-14T05:34:39.833 回答