我想知道如何将一个批处理文件中的变量集发送到另一个。例如,我有:
程序.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
的程序将显示来自第一个program.bat
的变量text
•更新• 还有另一种方法可以做到这一点,即在bat-it-self中写入变量,并使用其他bat读取带有变量的第一个bat。
- 通过使用reg add/reg查询(setx)
您可以使用setx
来执行此操作,但是,setx
中的值
只有在下一个实例/会话之后才可用,此时由cmd/powershell 设置
此外,可以使用reg add
:设置setx
注册地址:reg add HKCUEnvironment /v _amount /d "%amount%" /f
按集合:setx _amount "%amount%"
用于在下一个实例/会话之前读取值:
for /f "tokens=3 delims=^ " %%i in ('reg query HKCUEnvironment ^| findstr /i /c:"_amount"') do set _amount=%%i
因此,在另一个*实例/会话中,变量在系统中,只需在需要时执行:设置数量=%_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 HKCUEnvironment ^| 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 HKCUEnvironment /v _amount /f 2>nul >nul
- 通过使用文件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
- 通过将变量发送到直接启动文件.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-您可以通过调用来替换启动
您可以简单地使用第二个批处理文件中的变量(只要您从第一个批处理中调用它,因为call
ed进程在同一环境中运行/继承了start
ed进程中的环境)。
first.bat:
@echo off
set "test=Hello"
call second.bat
秒.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
秒.bat:
@echo off
echo parameter is: %1
(参数使用见call /?
)
(两个示例都使用call
或start
运行)