我需要在运行批处理文件时传递一个ID和密码,而不是将它们硬编码到文件中。

下面是命令行的样子:

test.cmd admin P@55w0rd > test-log.txt

当前回答

最近有个朋友问我这个问题,所以我想在这里发布一下我如何在批处理文件中处理命令行参数。

正如您将看到的,这种技术有一些开销,但它使我的批处理文件非常容易理解和快速实现。以及支持以下结构:

>template.bat [-f] [--flag] [--namedvalue value] arg1 [arg2][arg3][...]

它的jist包含:init、:parse和:main函数。

示例使用

>template.bat /?
test v1.23
This is a sample batch file template,
providing command-line arguments and flags.

USAGE:
test.bat [flags] "required argument" "optional argument"

/?, --help           shows this help
/v, --version        shows the version
/e, --verbose        shows detailed output
-f, --flag value     specifies a named parameter value

>template.bat          <- throws missing argument error
(same as /?, plus..)
****                                   ****
****    MISSING "REQUIRED ARGUMENT"    ****
****                                   ****

>template.bat -v
1.23

>template.bat --version
test v1.23
This is a sample batch file template,
providing command-line arguments and flags.

>template.bat -e arg1
**** DEBUG IS ON
UnNamedArgument:    "arg1"
UnNamedOptionalArg: not provided
NamedFlag:          not provided

>template.bat --flag "my flag" arg1 arg2
UnNamedArgument:    "arg1"
UnNamedOptionalArg: "arg2"
NamedFlag:          "my flag"

>template.bat --verbose "argument #1" --flag "my flag" second
**** DEBUG IS ON
UnNamedArgument:    "argument #1"
UnNamedOptionalArg: "second"
NamedFlag:          "my flag"

template.bat

@::!/dos/rocks
@echo off
goto :init

:header
    echo %__NAME% v%__VERSION%
    echo This is a sample batch file template,
    echo providing command-line arguments and flags.
    echo.
    goto :eof

:usage
    echo USAGE:
    echo   %__BAT_NAME% [flags] "required argument" "optional argument" 
    echo.
    echo.  /?, --help           shows this help
    echo.  /v, --version        shows the version
    echo.  /e, --verbose        shows detailed output
    echo.  -f, --flag value     specifies a named parameter value
    goto :eof

:version
    if "%~1"=="full" call :header & goto :eof
    echo %__VERSION%
    goto :eof

:missing_argument
    call :header
    call :usage
    echo.
    echo ****                                   ****
    echo ****    MISSING "REQUIRED ARGUMENT"    ****
    echo ****                                   ****
    echo.
    goto :eof

:init
    set "__NAME=%~n0"
    set "__VERSION=1.23"
    set "__YEAR=2017"

    set "__BAT_FILE=%~0"
    set "__BAT_PATH=%~dp0"
    set "__BAT_NAME=%~nx0"

    set "OptHelp="
    set "OptVersion="
    set "OptVerbose="

    set "UnNamedArgument="
    set "UnNamedOptionalArg="
    set "NamedFlag="

:parse
    if "%~1"=="" goto :validate

    if /i "%~1"=="/?"         call :header & call :usage "%~2" & goto :end
    if /i "%~1"=="-?"         call :header & call :usage "%~2" & goto :end
    if /i "%~1"=="--help"     call :header & call :usage "%~2" & goto :end

    if /i "%~1"=="/v"         call :version      & goto :end
    if /i "%~1"=="-v"         call :version      & goto :end
    if /i "%~1"=="--version"  call :version full & goto :end

    if /i "%~1"=="/e"         set "OptVerbose=yes"  & shift & goto :parse
    if /i "%~1"=="-e"         set "OptVerbose=yes"  & shift & goto :parse
    if /i "%~1"=="--verbose"  set "OptVerbose=yes"  & shift & goto :parse

    if /i "%~1"=="--flag"     set "NamedFlag=%~2"   & shift & shift & goto :parse
    if /i "%~1"=="-f"         set "NamedFlag=%~2"   & shift & shift & goto :parse

    if not defined UnNamedArgument     set "UnNamedArgument=%~1"     & shift & goto :parse
    if not defined UnNamedOptionalArg  set "UnNamedOptionalArg=%~1"  & shift & goto :parse

    shift
    goto :parse

:validate
    if not defined UnNamedArgument call :missing_argument & goto :end

:main
    if defined OptVerbose (
        echo **** DEBUG IS ON
    )

    echo UnNamedArgument:    "%UnNamedArgument%"

    if defined UnNamedOptionalArg      echo UnNamedOptionalArg: "%UnNamedOptionalArg%"
    if not defined UnNamedOptionalArg  echo UnNamedOptionalArg: not provided

    if defined NamedFlag               echo NamedFlag:          "%NamedFlag%"
    if not defined NamedFlag           echo NamedFlag:          not provided

:end
    call :cleanup
    exit /B

:cleanup
    REM The cleanup function is only really necessary if you
    REM are _not_ using SETLOCAL.
    set "__NAME="
    set "__VERSION="
    set "__YEAR="

    set "__BAT_FILE="
    set "__BAT_PATH="
    set "__BAT_NAME="

    set "OptHelp="
    set "OptVersion="
    set "OptVerbose="

    set "UnNamedArgument="
    set "UnNamedArgument2="
    set "NamedFlag="

    goto :eof

其他回答

没有必要把事情复杂化。例如,它只是命令%1 %2参数,

@echo off

xcopy %1 %2 /D /E /C /Q /H /R /K /Y /Z

echo copied %1 to %2

pause

“pause”显示批处理文件所做的工作,并等待您按下ANY键。将其保存为Windows文件夹中的xx.bat。

要使用它,输入,例如:

xx c:\f\30\*.* f:\sites\30

这个批处理文件负责所有必要的参数,比如只复制文件、更新的文件等等。在Windows出现之前,我就开始使用它了。如果您喜欢在复制文件时查看文件名,可以省略Q参数。

简单的解决方法(即使问题已经很老了)

Test1.bat

echo off
echo "Batch started"
set arg1=%1
echo "arg1 is %arg1%"
echo on
pause

CallTest1.bat

call "C:\Temp\Test1.bat" pass123

输出

YourLocalPath>call "C:\Temp\test.bat" pass123

YourLocalPath>echo off
"Batch started"
"arg1 is pass123"

YourLocalPath>pause
Press any key to continue . . .

其中YourLocalPath是当前目录路径。

为了简单起见,将命令参数存储在变量中,并使用变量进行比较。

它不仅写起来简单,而且维护起来也很简单,所以如果后来其他人或你在很长一段时间后阅读了你的脚本,它将很容易理解和维护。

内联编写代码:参见其他答案。

成对的参数

如果你喜欢在键值对中传递参数,你可以使用这样的方法:

@echo off

setlocal enableDelayedExpansion

:::::  asigning arguments as a key-value pairs:::::::::::::
set counter=0
for %%# in (%*) do (    
    set /a counter=counter+1
    set /a even=counter%%2
    
    if !even! == 0 (
        echo setting !prev! to %%#
        set "!prev!=%%~#"
    )
    set "prev=%%~#"
)
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:: showing the assignments
echo %one% %two% %three% %four% %five%

endlocal

举个例子:

c:>argumentsDemo.bat one 1 "two" 2 three 3 four 4 "five" 5
1 2 3 4 5

预定义的变量

您还可以提前设置一些环境变量。这可以通过在控制台或在我的电脑上设置来完成:

@echo off

if defined variable1 (
    echo %variable1%
)

if defined variable2 (
    echo %variable2%
)

像这样称呼它:

c:\>set variable1=1

c:\>set variable2=2

c:\>argumentsTest.bat
1
2

包含列出值的文件

您还可以指向预先设置所需值的文件。 如果这是脚本:

@echo off

setlocal
::::::::::
set "VALUES_FILE=E:\scripts\values.txt"
:::::::::::


for /f "usebackq eol=: tokens=* delims=" %%# in ("%VALUES_FILE%") do set "%%#"

echo %key1% %key2% %some_other_key%

endlocal

values文件是这样的:

:::: use EOL=: in the FOR loop to use it as a comment

key1=value1

key2=value2

:::: do not left spaces arround the =
:::: or at the begining of the line

some_other_key=something else

and_one_more=more

调用它的输出将是:

Value1 value2别的东西

当然,您可以结合所有方法。检查参数语法,shift

要在命令行中引用一个set变量,你需要使用%a%,例如:

set a=100 
echo %a%  
rem output = 100 

注意:这适用于Windows 7 pro。

对于使用循环获取所有参数并纯批处理:

注意事项:用于不带:?*&|<>


@echo off && setlocal EnableDelayedExpansion

 for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && (
     call set "_arg_[!_cnt!]=!_arg_!" && for /l %%l in (!_cnt! 1 !_cnt!
     )do echo/ The argument n:%%l is: !_arg_[%%l]!
 )

goto :eof 

你的代码已经准备好在需要的地方用参数号做一些事情,比如……

 @echo off && setlocal EnableDelayedExpansion

 for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && call set "_arg_[!_cnt!]=!_arg_!"
 
 fake-command /u !_arg_[1]! /p !_arg_[2]! > test-log.txt