call batch file from another passing parameters

后端 未结 3 457
渐次进展
渐次进展 2021-01-01 17:14

I have the following batch file that when run asks the user for input. This works fine.

@REM Sample batch file
SET PARAM1=\"\"
SET PARAM2=\"\"
SET /P PARAM1=         


        
3条回答
  •  迷失自我
    2021-01-01 17:49

    I believe you want something like this?

    @echo off
    
    :: Fetch param1
    set "param1=%~1"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter parameter 1: "
    :param1Check
    if "%param1%"=="" goto :param1Prompt
    
    :: Fetch param2    
    set "param2=%~2"
    goto :param2Check
    :param2Prompt
    set /p "param2=Enter parameter 2: "
    :param2Check
    if "%param2%"=="" goto :param2Prompt
    
    :: Process the params
    echo param1=%param1%
    echo param2=%param2%
    

    Test.bat run without arguments:

    >>test.bat
    Enter parameter 1: foo
    Enter parameter 2: bar
    param1=foo
    param2=bar
    

    Test.bat run with arguments:

    >>test.bat foo bar
    param1=foo
    param2=bar
    

    Alternative, using environment variables instead of command line arguments (see also ppumkin's answer):

    @echo off  
    
    :: Fetch param1  
    **set "param1=%globalparam1%"**  
    goto :param1Check  
    :param1Prompt  
    set /p "param1=Enter parameter 1: "  
    :param1Check  
    if "%param1%"=="" goto :param1Prompt  
    
    :: Fetch param2    
    **set "param2=%globalparam2%"**  
    goto :param2Check  
    :param2Prompt  
    set /p "param2=Enter parameter 2: "  
    :param2Check  
    if "%param2%"=="" goto :param2Prompt  
    
    :: Process the params  
    echo param1=%param1%  
    echo param2=%param2%
    

    Just set the environment variables globalparam1 and globalparam2 in your environment or your calling batch file to suppress the prompting:

    Test.bat run without setting environment variables:

    >>test.bat
    Enter parameter 1: foo
    Enter parameter 2: bar
    param1=foo
    param2=bar
    

    Test.bat run with setting environment variables:

    >>set globalparam1=foo
    
    >>set globalparam2=bar
    
    >>test
    param1=foo
    param2=bar
    

    Note: setting the environment variables can also be done in e.g. a calling batch script.

提交回复
热议问题