如何在批处理程序之间移动变量

时间:2019-02-10 19:01:06

标签: batch-file

我想知道如何将一个批处理文件中的变量集发送到另一个。例如,我有:

program.bat

@echo off
set /p amount="Amount:"
set a=0
set /p text="Text:"
:loop
set /a a+=1
start myecho.bat
if %a% LSS %amount%
exit

现在第二个名为myecho.bat的程序将显示第一个text中的变量program.bat

2 个答案:

答案 0 :(得分:3)

• Update • 还有一种另一种方式,通过将变量自写为自己 >,然后使用另一个蝙蝠来读取带有变量的第一个蝙蝠

  

1)通过使用reg add / reg查询(setx)

您可以使用 setx 来执行此操作,但是 setx

中的值

仅在设置了下一个 instance / session 之后通过cmd / powershell

可用。

还可以使用 setx 设置 reg add

通过reg添加:`reg添加HKCU \环境/ v _amount / d “%amount%” / f

通过设置setx命令: setx _amount“%amount%”

要读取下一个 instance / session 之前的值:     为/ f“ tokens = 3 delims = ^” %% i in('reg query HKCU \ Environment ^ | findstr / i / c:“ _ amount”')设置_amount = %% i

因此,在另一个* instance / session中,变量位于系统中,只需在需要时执行:设置数量=%_ amount%

@echo off
set /p amount="Amount:"
setx _amount "%amount%"
set a=0
set /p text="Text:"
:loop
set /a a+=1

start myecho.bat 

:: add this lines lines if ..( ...)  in file "myecho.bat" :: 
if "./%_amount%/." equ ".//." (

     for /f "tokens=3 delims=^ " %%i in ('reg query HKCU\Environment ^| findstr /i /c:"_amount"') do set _amount=%%i

     ) else (

     set amount=%_amount%

     )

  if %a% LSS %amount% echo/ do some thing
  exit

当不再需要该变量时,可以通过以下方式删除/删除setx / reg键:

reg delete HKCU\Environment /v _amount /f 2>nul >nul

  

2)通过使用txt文件保存并读取...

用第一个蝙蝠在%temp%\ file.txt中写入值,然后用第二个蝙蝠读取:

@echo off
set /p amount="Amount:"
echo/%amount%>"%temp%\amount_value_in.txt"
set a=0
set /p text="Text:"
:loop
set /a a+=1

start myecho.bat 

:: add this lines lines if ..( ...)  in file "myecho.bat" :: 

set /p amount=<"%temp%\amount_value_in.txt"

if %a% LSS %amount% echo/ do some thing

exit
  

3)通过send变量直接与起始file.bat%amount%...

@echo off
set /p amount="Amount:"
echo/%amount%>"%temp%\amount_value_in.txt"
set a=0
set /p text="Text:"
:loop
set /a a+=1

start myecho.bat %amount% 

:: add this lines lines if ..( ...)  in file "myecho.bat" :: 
set amount=%1      
if %a% LSS %amount% echo/ do some thing
exit

糟糕:

1-对不起,我有限的英语

2-您可以将 start 替换为 call

答案 1 :(得分:2)

您可以简单地在第二个批处理文件中使用该变量(,只要您从第一个文件调用它即可,因为call ed进程在同一环境中运行/继承了该环境在start版本的过程中)。

first.bat:

@echo off
set "test=Hello"
call second.bat 

second.bat:

echo variable 'test' is: %test%

如果要传递变量的值,最好使用参数:

first.bat:

@echo off
set "test=Hello"
call second.bat %test%
REM that's the same as:
call second.bat Hello

second.bat:

@echo off
echo parameter is: %1

(有关参数的使用,请参见call /?

(两个示例都以callstart运行)