How can I pass arguments to a batch file?

后端 未结 18 2163
陌清茗
陌清茗 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:30

    Accessing batch parameters can be simple with %1, %2, ... %9 or also %*,
    but only if the content is simple.

    There is no simple way for complex contents like "&"^&, as it's not possible to access %1 without producing an error.

    set  var=%1
    set "var=%1"
    set  var=%~1
    set "var=%~1"
    

    The lines expand to

    set  var="&"&
    set "var="&"&"
    set  var="&"&
    set "var="&"&"
    

    And each line fails, as one of the & is outside of the quotes.

    It can be solved with reading from a temporary file a remarked version of the parameter.

    @echo off
    SETLOCAL DisableDelayedExpansion
    
    SETLOCAL
    for %%a in (1) do (
        set "prompt="
        echo on
        for %%b in (1) do rem * #%1#
        @echo off
    ) > param.txt
    ENDLOCAL
    
    for /F "delims=" %%L in (param.txt) do (
      set "param1=%%L"
    )
    SETLOCAL EnableDelayedExpansion
    set "param1=!param1:*#=!"
    set "param1=!param1:~0,-2!"
    echo %%1 is '!param1!'
    

    The trick is to enable echo on and expand the %1 after a rem statement (works also with %2 .. %*).
    So even "&"& could be echoed without producing an error, as it is remarked.

    But to be able to redirect the output of the echo on, you need the two for-loops.

    The extra characters * # are used to be safe against contents like /? (would show the help for REM).
    Or a caret ^ at the line end could work as a multiline character, even in after a rem.

    Then reading the rem parameter output from the file, but carefully.
    The FOR /F should work with delayed expansion off, else contents with "!" would be destroyed.
    After removing the extra characters in param1, you got it.

    And to use param1 in a safe way, enable the delayed expansion.

提交回复
热议问题