具有相同变量的多个批处理文件

时间:2015-02-18 13:05:37

标签: variables batch-file cmd call

我想知道是否可能在2个不同的批处理程序中使用相同的变量。

    :home
    Set /p Name=What is your Name? 
    Set /p Com=What Command do you wish to use?
    If %Com% == #HELP goto msgbox
    (MORE IF's ARE USED)

    goto msgbox

    :msgbox
    cls
    start msgbox.cmd
    Echo Welcome to the MSGBOX PROGRAM %Name%
    %Com% Code was typed, here is the Help file
    goto Help

    :Help
    cls
    (display's the help for program)
    Set /p return=Would you like to return?
    If %return%==Y goto home
    If %return%==N goto exit
    (Set errorlevel==1 if no selection)

    :exit
    cls
    Echo press Enter to exit program
    pause >nul

1 个答案:

答案 0 :(得分:1)

1)如果从第一个调用第二个bat文件,第二个将继承所有变量。

2)您还可以定义环境变量。您可以使用SETX命令

setx variable value

虽然它是在注册表中编写的,但你不能直接使用它 - 它可以在下一个cmd会话中访问。所以你需要在脚本中使用临时变量:

Set /p Com=What Command do you wish to use?
rem making variable accessible for the next run or for another batch
setx Com %com%

您可以使用set覆盖所需的每个cmd会话或脚本的值。之后它将再次使用注册表值。

3)您还可以使用临时文件,但这需要在下一批中阅读:

Set /p Com=What Command do you wish to use?
echo %com%>c:\command.file

在下一个脚本中你需要使用:

for /f "useback tokens=* delims=" %%# in ("c:\command.file") do set "com=%%#"