如何将变量从一个批处理文件传递到另一个批处理文件?

时间:2014-12-22 01:06:48

标签: batch-file

如何编写一个批处理文件,该文件获取输入变量并将其发送到另一个批处理文件进行处理。

第1批

我不知道如何将变量发送到批次2,这是我的问题。

第2批

if %variable%==1 goto Example
goto :EOF

:Example
echo YaY

3 个答案:

答案 0 :(得分:12)

您可以将batch1.bat变量作为参数传递给batch2.bat。

<强> arg_batch1.bat

@echo off
cls

set file_var1=world
set file_var2=%computername%
call arg_batch2.bat %file_var1% %file_var2%

:: Note that after batch2.bat runs, the flow returns here, but since there's
:: nothing left to run, the code ends, giving the appearance of ending with
:: batch2.bat being the end of the code.

<强> arg_batch2.bat

@echo off

:: There should really be error checking here to ensure a
:: valid string is passed, but this is just an example.
set arg1=%~1
set arg2=%~2

echo Hello, %arg1%! My name is %arg2%.

如果您需要同时运行脚本,可以使用临时文件。

<强> file_batch1.bat

@echo off
set var=world

:: Store the variable name and value in the form var=value
:: > will overwrite any existing data in args.txt, use >> to add to the end
echo var1=world>args.txt
echo var2=%COMPUTERNAME%>>args.txt

call file_batch2.bat

<强> file_batch2.bat

@echo off
cls

:: Get the variable value from args.txt
:: Again, there is ideally some error checking here, but this is an example
:: Set no delimiters so that the entire line is processed at once
for /f "delims=" %%A in (args.txt) do (
    set %%A
)

echo Hello, %var1%! My name is %var2%.

答案 1 :(得分:11)

你根本不需要做任何事情。批处理文件中设置的变量在它调用的批处理文件中可见。

实施例

test1.bat

@echo off
set x=7
call test2.bat
set x=3
call test2.bat
pause

test2.bat

echo In test2.bat with x = %x%.

输出

...当test1.bat运行时。

In test2.bat with x = 7.
In test2.bat with x = 3.
Press any key to continue . . .

答案 2 :(得分:0)

您可以从下面找到解决方案 -

variable goes here >> "second file goes here.bat"

这段代码的作用是将变量写入第二个文件(如果不存在。即使它不存在,它也会创建一个新文件。