How to pass variables from one batch file to another batch file?

后端 未结 3 1023
面向向阳花
面向向阳花 2021-01-02 02:26

How do I write a batch file which gets an input variable and sends it to another batch file to be processed.

Batch 1

I don\'t know how to se

3条回答
  •  一生所求
    2021-01-02 03:09

    You can pass in the batch1.bat variables as arguments to 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%.
    

    If you need to run the scripts simultaneously, you can use a temporary file.

    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%.
    

提交回复
热议问题