How can I pass arguments to a batch file?

后端 未结 18 2165
陌清茗
陌清茗 2020-11-22 02:53

I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file.

Here\'s what the command line looks like:

18条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 03:16

    I wrote a simple read_params script that can be called as a function (or external .bat) and will put all variables into the current environment. It won't modify the original parameters because the function is being called with a copy of the original parameters.

    For example, given the following command:

    myscript.bat some -random=43 extra -greeting="hello world" fluff
    

    myscript.bat would be able to use the variables after calling the function:

    call :read_params %*
    
    echo %random%
    echo %greeting%
    

    Here's the function:

    :read_params
    if not %1/==/ (
        if not "%__var%"=="" (
            if not "%__var:~0,1%"=="-" (
                endlocal
                goto read_params
            )
            endlocal & set %__var:~1%=%~1
        ) else (
            setlocal & set __var=%~1
        )
        shift
        goto read_params
    )
    exit /B
    

    Limitations

    • Cannot load arguments with no value such as -force. You could use -force=true but I can't think of a way to allow blank values without knowing a list of parameters ahead of time that won't have a value.

    Changelog

    • 2/18/2016
      • No longer requires delayed expansion
      • Now works with other command line arguments by looking for - before parameters.

提交回复
热议问题