批处理文件调用子批处理文件以传递n个参数并在不使用文件的情况下返回

The*_*Cat 22 batch-file

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

我看着

@FOR /F "tokens=*" %%i IN ('%find_OS_version%') DO SET OS_VER=%%i
Run Code Online (Sandbox Code Playgroud)

Call function/batch %arg1% %arg2%
Run Code Online (Sandbox Code Playgroud)

我没有看到我如何设置这样做

编辑: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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

dbe*_*ham 43

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

1)通过使用EXIT /B n其中n =某个数字,可以通过errorlevel返回单个整数值.

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

:sum
setlocal
set /a "rtn=%1 + %2"
exit /b %rtn%
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

要存储答案的变量的名称可以作为参数传递!中间值可以隐藏在主程序中.

@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
Run Code Online (Sandbox Code Playgroud)

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

更新

以上仍然可以返回的内容有限制.有关基于FOR的支持更广泛值的替代方法,请参阅/sf/answers/577803201/.请参阅/sf/answers/578056601/,了解"魔法"技术,在任何情况下都可以安全地返回任何长度<~8190的值.


bef*_*fzz 5

提示

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

:LABEL
EXIT /B 5
Run Code Online (Sandbox Code Playgroud)

输出将是:

1: 0
2: 5
3: 5
Run Code Online (Sandbox Code Playgroud)

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