如何将命令行参数传递给批处理文件?

时间:2023-02-02 19:24:35

I need to pass id and password to a cmd (or bat) file at the time of running rather than hardcoding them into the file.

我需要在运行时将id和密码传递给cmd(或bat)文件,而不是硬编码到文件中。

Here's what the command line looks like:

命令行如下所示:

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

14 个解决方案

#1


785  

Another useful tip is to use %* to mean "all". For example,

另一个有用的技巧是使用%*表示“所有”。例如,

echo offset arg1=%1set arg2=%2shiftshiftfake-command /u %arg1% /p %arg2% %*

When you run:

当您运行:

test-command admin password foo bar

the above batch file will run:

上述批处理文件将运行:

fake-command /u admin /p password foo bar

I may have the syntax slightly wrong, but this is the general idea.

我的语法可能有点错误,但这是一般的想法。

#2


220  

Here's how I do it.

我是这么做的。

@fake-command /u %1 /p %2

Here's what the command line looks like:

命令行如下所示:

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

The %1 applies to the first parameter the %2 (and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way.

%1适用于第一个参数%2(这里有一个棘手的部分)适用于第二个参数。您可以用这种方式传递多达9个参数。

#3


116  

If you want to intelligently handle missing parameters you can do something like:

如果你想聪明地处理缺失的参数,你可以做以下事情:

IF %1.==. GOTO No1IF %2.==. GOTO No2... do stuff...GOTO End1:No1  ECHO No param 1GOTO End1:No2  ECHO No param 2GOTO End1:End1

#4


70  

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

访问批处理参数可以很简单,%1,%2,…%9或%*,但仅当内容简单时。

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

没有简单的方法对于复杂的内容像^ &“&”,因为它是不可能访问% 1没有产生一个错误。

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

The lines expands 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 offSETLOCAL DisableDelayedExpansionSETLOCALfor %%a in (1) do (    set "prompt="    echo on    for %%b in (1) do rem * #%1#    @echo off) > param.txtENDLOCALfor /F "delims=" %%L in (param.txt) do (  set "param1=%%L")SETLOCAL EnableDelayedExpansionset "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.

诀窍是在rem语句之后启用echo并扩展%1(同样适用于%2)。% *)。因此,即使是“&”也可以在不产生错误的情况下进行回显。

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

但是要重定向echo的输出,需要使用两个for循环。

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.

额外的字符* #用于对诸如/?(这对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.

然后从文件中读取rem参数输出,但要小心。FOR /F应该与延迟扩展关闭一起工作,否则带有“!”的内容将被销毁。在删除了param1中的额外字符之后,你就得到了。

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

为了安全地使用param1,可以延迟扩张。

#5


47  

Yep, and just don't forget to use variables like %%1 when using if and for and the gang.

是的,在使用if和for和gang时不要忘记使用%1这样的变量。

If you forget the double %, then you will be substituting in (possibly null) command line arguments and you will receive some pretty confusing error messages.

如果您忘记了double %,那么您将代入(可能为null)命令行参数,您将收到一些非常混乱的错误消息。

#6


44  

There is no need to complicate it. It is simply command %1 %2 parameters, for example,

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

@echo offxcopy %1 %2 /D /E /C /Q /H /R /K /Y /Zecho copied %1 to %2pause

The "pause" displays what the batch file has done and waits for you to hit the ANY key. Save that as xx.bat in the Windows folder.

“暂停”显示批处理文件所做的工作,并等待您按任意键。保存为xx。在Windows文件夹中输入bat。

To use it, type, for example:

要使用它,输入,例如:

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

This batch file takes care of all the necessary parameters, like copying only files, that are newer, etc. I have used it since before Windows. If you like seeing the names of the files, as they are being copied, leave out the Q parameter.

这个批处理文件负责所有必要的参数,比如只复制更新的文件等。如果您喜欢看到文件的名称,因为它们正在被复制,请忽略Q参数。

#7


29  

@ECHO OFF:LoopIF "%1"=="" GOTO ContinueSHIFTGOTO Loop:Continue

Note: IF "%1"=="" will cause problems if %1 is enclosed in quotes itself.

注:如果"%1"= "将导致问题,如果%1包含在引号中。

In that case, use IF [%1]==[] or, in NT 4 (SP6) and later only, IF "%~1"=="" instead.

在这种情况下,使用IF[%1]=[]或,在NT 4 (SP6)中,然后只使用“%~1”=“”。

#8


21  

A friend was asking me about this subject recently, so I thought I'd post how I handle command-line arguments in batch files.

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

This technique has a bit of overhead as you'll see, but it makes my batch files very easy to understand and quick to implement. As well as supporting the following structures:

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

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

The jist of it is having the :init, :parse, and :main functions.

它的第一个函数是:init、:parse和:main函数。

Example usage

示例使用

>template.bat /?test v1.23This 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 -v1.23>template.bat --versiontest v1.23This is a sample batch file template,providing command-line arguments and flags.>template.bat -e arg1**** DEBUG IS ONUnNamedArgument:    "arg1"UnNamedOptionalArg: not providedNamedFlag:          not provided>template.bat --flag "my flag" arg1 arg2UnNamedArgument:    "arg1"UnNamedOptionalArg: "arg2"NamedFlag:          "my flag">template.bat --verbose "argument #1" --flag "my flag" second**** DEBUG IS ONUnNamedArgument:    "argument #1"UnNamedOptionalArg: "second"NamedFlag:          "my flag"

template.bat

template.bat

@::!/dos/rocks@echo offgoto :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 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

#9


17  

Let's keep this simple.

让我们保持这个简单。

Here is the .cmd file.

这是。cmd文件。

@echo offrem this file is named echo_3params.cmdecho %1echo %2echo %3set v1=%1set v2=%2set v3=%3echo v1 equals %v1%echo v2 equals %v2%echo v3 equals %v3%

Here are 3 calls from the command line.

下面是来自命令行的3个调用。

C:\Users\joeco>echo_3params 1abc 2 def  3 ghi1abc2defv1 equals 1abcv2 equals 2v3 equals defC:\Users\joeco>echo_3params 1abc "2 def"  "3 ghi"1abc"2 def""3 ghi"v1 equals 1abcv2 equals "2 def"v3 equals "3 ghi"C:\Users\joeco>echo_3params 1abc '2 def'  "3 ghi"1abc'2def'v1 equals 1abcv2 equals '2v3 equals def'C:\Users\joeco>

#10


15  

FOR %%A IN (%*) DO (    REM Now your batch file handles %%A instead of %1    REM No need to use SHIFT anymore.    ECHO %%A)

This loops over the batch parameters (%*) either they are quoted or not, then echos each parameter.

循环遍历批处理参数(%*),要么引用,要么不引用,然后对每个参数进行回声。

#11


15  

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.

我编写了一个简单的read_params脚本,可以将其称为函数(或外部.bat),并将所有变量放入当前环境中。它不会修改原始参数,因为用原始参数的副本调用函数。

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:

myscript。bat在调用函数后可以使用变量:

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

Here's the function:

的功能:

:read_paramsif 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.
  • 不能加载没有值(如-force)的参数。您可以使用-force=true,但是我想不出一种允许空白值的方法,如果不事先知道没有值的参数列表。

Changelog

更新日志

  • 2/18/2016
    • No longer requires delayed expansion
    • 不再需要延迟扩张
    • Now works with other command line arguments by looking for - before parameters.
    • 现在通过查找- before参数与其他命令行参数一起工作。
  • 2/18/2016不再需要延迟扩展,现在可以通过查找- before参数与其他命令行参数一起工作。

#12


7  

To refer to a set variable in command line you would need to use " %a% " so for example:

要引用命令行中的set变量,需要使用“%a%”,例如:

      set a=100       echo %a%        output = 100 

Note: This works for Windows 7 pro.

注意:这适用于Windows 7 pro。

#13


3  

Make a new batch file (example: openclass.bat) and write this line in the file:

创建一个新的批处理文件(例如:openclass.bat),并在文件中写入这一行:

java %~n1

Then place the batch file in, let's say, the system32 folder, go to your Java class file, right click, Properties, Open with..., then find your batch file, select it and that's that...

然后将批处理文件放入,比方说,system32文件夹,进入Java类文件,右键单击,Properties, Open with…,然后找到您的批处理文件,选择它,那就是……

It works for me.

它适合我。

PS: I can't find a way to close the cmd window when I close the Java class. For now...

PS:当我关闭Java类时,我找不到关闭cmd窗口的方法。现在……

#14


1  

Inspired by an answer elsewhere by @Jon, I have crafted a more general algorithm for extracting named parameters, optional values, and switches.

受@Jon的回答启发,我设计了一个更通用的算法来提取命名参数、可选值和开关。

Let us say that we want to implement a utility foobar. It requires an initial command. It has an optional parameter --foo which takes an optional value (which cannot be another parameter, of course); if the value is missing it defaults to default. It also has an optional parameter --bar which takes a required value. Lastly it can take a flag --baz with no value allowed. Oh, and these parameters can come in any order.

假设我们想要实现一个实用的foobar。它需要一个初始命令。它有一个可选参数——foo它取一个可选值(当然不能是另一个参数);如果值丢失,则默认为默认值。它还有一个可选参数——bar,它接受一个必需的值。最后,它可以取一个标志——baz,不允许有任何值。哦,这些参数可以是任意顺序的。

In other words, it looks like this:

换句话说,它是这样的:

foobar <command> [--foo [<fooval>]] [--bar <barval>] [--baz]

Here is a solution:

这是一个解决方案:

@ECHO OFFSETLOCALREM FooBar parameter demoREM By Garret WilsonSET CMD=%~1IF "%CMD%" == "" (  GOTO usage)SET FOO=SET DEFAULT_FOO=defaultSET BAR=SET BAZ=SHIFT:argsSET PARAM=%~1SET ARG=%~2IF "%PARAM%" == "--foo" (  SHIFT  IF NOT "%ARG%" == "" (    IF NOT "%ARG:~0,2%" == "--" (      SET FOO=%ARG%      SHIFT    ) ELSE (      SET FOO=%DEFAULT_FOO%    )  ) ELSE (    SET FOO=%DEFAULT_FOO%  )) ELSE IF "%PARAM%" == "--bar" (  SHIFT  IF NOT "%ARG%" == "" (    SET BAR=%ARG%    SHIFT  ) ELSE (    ECHO Missing bar value. 1>&2    ECHO:    GOTO usage  )) ELSE IF "%PARAM%" == "--baz" (  SHIFT  SET BAZ=true) ELSE IF "%PARAM%" == "" (  GOTO endargs) ELSE (  ECHO Unrecognized option %1. 1>&2  ECHO:  GOTO usage)GOTO args:endargsECHO Command: %CMD%IF NOT "%FOO%" == "" (  ECHO Foo: %FOO%)IF NOT "%BAR%" == "" (  ECHO Bar: %BAR%)IF "%BAZ%" == "true" (  ECHO Baz)REM TODO do something with FOO, BAR, and/or BAZGOTO :eof:usageECHO FooBarECHO Usage: foobar ^<command^> [--foo [^<fooval^>]] [--bar ^<barval^>] [--baz]EXIT /B 1
  • Use SETLOCAL so that the variables don't escape into the calling environment.
  • 使用SETLOCAL,使变量不会转义到调用环境中。
  • Don't forget to initialize the variables SET FOO=, etc. in case someone defined them in the calling environment.
  • 不要忘记初始化变量SET FOO=等,以防有人在调用环境中定义它们。
  • Use %~1 to remove quotes.
  • 使用%~1删除引号。
  • Use IF "%ARG%" == "" and not IF [%ARG%] == [] because [ and ] don't play will at all with values ending in a space.
  • 使用IF "%ARG%" = ",而不使用IF [%ARG%] =[],因为[和]不会播放,值以空格结尾。
  • Even if you SHIFT inside an IF block, the current args such as %~1 don't get updated because they are determined when the IF is parsed. You could use %~1 and %~2 inside the IF block, but it would be confusing because you had a SHIFT. You could put the SHIFT at the end of the block for clarity, but that might get lost and/or confuse people as well. So "capturing" %~1 and %~1 outside the block seems best.
  • 即使在if块中移动,当前的args(如%~1)也不会被更新,因为它们是在解析if时确定的。您可以在IF块中使用%~1和%~2,但是这会让您感到困惑,因为您有一个移位。你可以在代码块的末尾进行转换以获得清晰性,但是这可能会丢失或者迷惑人。因此,在块外“捕获”%~1和%~1似乎是最好的。
  • You don't want to use a parameter in place of another parameter's optional value, so you have to check IF NOT "%ARG:~0,2%" == "--".
  • 您不希望使用一个参数代替另一个参数的可选值,因此您必须检查是否“%ARG:~0,2%”=“-”。
  • Be careful only to SHIFT when you use one of the parameters.
  • 只有在使用其中一个参数时才要小心移位。
  • The duplicate code SET FOO=%DEFAULT_FOO% is regrettable, but the alternative would be to add an IF "%FOO%" == "" SET FOO=%DEFAULT_FOO% outside the IF NOT "%ARG%" == "" block. However because this is still inside the IF "%PARAM%" == "--foo" block, the %FOO% value would have been evaluated and set before you ever entered the block, so you would never detect that both the --foo parameter was present and also that the %FOO% value was missing.
  • 重复的代码设置FOO=%DEFAULT_FOO%是令人遗憾的,但是另一种选择是在IF“%FOO%”= " SET FOO=%DEFAULT_FOO =%DEFAULT_FOO%不在IF“%ARG%”=“”块外面添加一个IF“%FOO% FOO%”=“”。但是,因为它仍然在IF“%PARAM%”=“-foo”块中,所以在您进入该块之前,% foo %的值将被计算和设置,所以您永远不会检测到-foo参数都存在,而且% foo %的值也丢失了。
  • Note that ECHO Missing bar value. 1>&2 sends the error message to stderr.
  • 注意,回波缺少bar值。>和2向stderr发送错误消息。
  • Want a blank line in a Windows batch file? You gotta use ECHO: or one of the variations.
  • 想要Windows批处理文件中的空行吗?你必须使用ECHO:或者其中的一个变体。

#1


785  

Another useful tip is to use %* to mean "all". For example,

另一个有用的技巧是使用%*表示“所有”。例如,

echo offset arg1=%1set arg2=%2shiftshiftfake-command /u %arg1% /p %arg2% %*

When you run:

当您运行:

test-command admin password foo bar

the above batch file will run:

上述批处理文件将运行:

fake-command /u admin /p password foo bar

I may have the syntax slightly wrong, but this is the general idea.

我的语法可能有点错误,但这是一般的想法。

#2


220  

Here's how I do it.

我是这么做的。

@fake-command /u %1 /p %2

Here's what the command line looks like:

命令行如下所示:

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

The %1 applies to the first parameter the %2 (and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way.

%1适用于第一个参数%2(这里有一个棘手的部分)适用于第二个参数。您可以用这种方式传递多达9个参数。

#3


116  

If you want to intelligently handle missing parameters you can do something like:

如果你想聪明地处理缺失的参数,你可以做以下事情:

IF %1.==. GOTO No1IF %2.==. GOTO No2... do stuff...GOTO End1:No1  ECHO No param 1GOTO End1:No2  ECHO No param 2GOTO End1:End1

#4


70  

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

访问批处理参数可以很简单,%1,%2,…%9或%*,但仅当内容简单时。

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

没有简单的方法对于复杂的内容像^ &“&”,因为它是不可能访问% 1没有产生一个错误。

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

The lines expands 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 offSETLOCAL DisableDelayedExpansionSETLOCALfor %%a in (1) do (    set "prompt="    echo on    for %%b in (1) do rem * #%1#    @echo off) > param.txtENDLOCALfor /F "delims=" %%L in (param.txt) do (  set "param1=%%L")SETLOCAL EnableDelayedExpansionset "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.

诀窍是在rem语句之后启用echo并扩展%1(同样适用于%2)。% *)。因此,即使是“&”也可以在不产生错误的情况下进行回显。

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

但是要重定向echo的输出,需要使用两个for循环。

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.

额外的字符* #用于对诸如/?(这对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.

然后从文件中读取rem参数输出,但要小心。FOR /F应该与延迟扩展关闭一起工作,否则带有“!”的内容将被销毁。在删除了param1中的额外字符之后,你就得到了。

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

为了安全地使用param1,可以延迟扩张。

#5


47  

Yep, and just don't forget to use variables like %%1 when using if and for and the gang.

是的,在使用if和for和gang时不要忘记使用%1这样的变量。

If you forget the double %, then you will be substituting in (possibly null) command line arguments and you will receive some pretty confusing error messages.

如果您忘记了double %,那么您将代入(可能为null)命令行参数,您将收到一些非常混乱的错误消息。

#6


44  

There is no need to complicate it. It is simply command %1 %2 parameters, for example,

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

@echo offxcopy %1 %2 /D /E /C /Q /H /R /K /Y /Zecho copied %1 to %2pause

The "pause" displays what the batch file has done and waits for you to hit the ANY key. Save that as xx.bat in the Windows folder.

“暂停”显示批处理文件所做的工作,并等待您按任意键。保存为xx。在Windows文件夹中输入bat。

To use it, type, for example:

要使用它,输入,例如:

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

This batch file takes care of all the necessary parameters, like copying only files, that are newer, etc. I have used it since before Windows. If you like seeing the names of the files, as they are being copied, leave out the Q parameter.

这个批处理文件负责所有必要的参数,比如只复制更新的文件等。如果您喜欢看到文件的名称,因为它们正在被复制,请忽略Q参数。

#7


29  

@ECHO OFF:LoopIF "%1"=="" GOTO ContinueSHIFTGOTO Loop:Continue

Note: IF "%1"=="" will cause problems if %1 is enclosed in quotes itself.

注:如果"%1"= "将导致问题,如果%1包含在引号中。

In that case, use IF [%1]==[] or, in NT 4 (SP6) and later only, IF "%~1"=="" instead.

在这种情况下,使用IF[%1]=[]或,在NT 4 (SP6)中,然后只使用“%~1”=“”。

#8


21  

A friend was asking me about this subject recently, so I thought I'd post how I handle command-line arguments in batch files.

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

This technique has a bit of overhead as you'll see, but it makes my batch files very easy to understand and quick to implement. As well as supporting the following structures:

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

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

The jist of it is having the :init, :parse, and :main functions.

它的第一个函数是:init、:parse和:main函数。

Example usage

示例使用

>template.bat /?test v1.23This 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 -v1.23>template.bat --versiontest v1.23This is a sample batch file template,providing command-line arguments and flags.>template.bat -e arg1**** DEBUG IS ONUnNamedArgument:    "arg1"UnNamedOptionalArg: not providedNamedFlag:          not provided>template.bat --flag "my flag" arg1 arg2UnNamedArgument:    "arg1"UnNamedOptionalArg: "arg2"NamedFlag:          "my flag">template.bat --verbose "argument #1" --flag "my flag" second**** DEBUG IS ONUnNamedArgument:    "argument #1"UnNamedOptionalArg: "second"NamedFlag:          "my flag"

template.bat

template.bat

@::!/dos/rocks@echo offgoto :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 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

#9


17  

Let's keep this simple.

让我们保持这个简单。

Here is the .cmd file.

这是。cmd文件。

@echo offrem this file is named echo_3params.cmdecho %1echo %2echo %3set v1=%1set v2=%2set v3=%3echo v1 equals %v1%echo v2 equals %v2%echo v3 equals %v3%

Here are 3 calls from the command line.

下面是来自命令行的3个调用。

C:\Users\joeco>echo_3params 1abc 2 def  3 ghi1abc2defv1 equals 1abcv2 equals 2v3 equals defC:\Users\joeco>echo_3params 1abc "2 def"  "3 ghi"1abc"2 def""3 ghi"v1 equals 1abcv2 equals "2 def"v3 equals "3 ghi"C:\Users\joeco>echo_3params 1abc '2 def'  "3 ghi"1abc'2def'v1 equals 1abcv2 equals '2v3 equals def'C:\Users\joeco>

#10


15  

FOR %%A IN (%*) DO (    REM Now your batch file handles %%A instead of %1    REM No need to use SHIFT anymore.    ECHO %%A)

This loops over the batch parameters (%*) either they are quoted or not, then echos each parameter.

循环遍历批处理参数(%*),要么引用,要么不引用,然后对每个参数进行回声。

#11


15  

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.

我编写了一个简单的read_params脚本,可以将其称为函数(或外部.bat),并将所有变量放入当前环境中。它不会修改原始参数,因为用原始参数的副本调用函数。

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:

myscript。bat在调用函数后可以使用变量:

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

Here's the function:

的功能:

:read_paramsif 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.
  • 不能加载没有值(如-force)的参数。您可以使用-force=true,但是我想不出一种允许空白值的方法,如果不事先知道没有值的参数列表。

Changelog

更新日志

  • 2/18/2016
    • No longer requires delayed expansion
    • 不再需要延迟扩张
    • Now works with other command line arguments by looking for - before parameters.
    • 现在通过查找- before参数与其他命令行参数一起工作。
  • 2/18/2016不再需要延迟扩展,现在可以通过查找- before参数与其他命令行参数一起工作。

#12


7  

To refer to a set variable in command line you would need to use " %a% " so for example:

要引用命令行中的set变量,需要使用“%a%”,例如:

      set a=100       echo %a%        output = 100 

Note: This works for Windows 7 pro.

注意:这适用于Windows 7 pro。

#13


3  

Make a new batch file (example: openclass.bat) and write this line in the file:

创建一个新的批处理文件(例如:openclass.bat),并在文件中写入这一行:

java %~n1

Then place the batch file in, let's say, the system32 folder, go to your Java class file, right click, Properties, Open with..., then find your batch file, select it and that's that...

然后将批处理文件放入,比方说,system32文件夹,进入Java类文件,右键单击,Properties, Open with…,然后找到您的批处理文件,选择它,那就是……

It works for me.

它适合我。

PS: I can't find a way to close the cmd window when I close the Java class. For now...

PS:当我关闭Java类时,我找不到关闭cmd窗口的方法。现在……

#14


1  

Inspired by an answer elsewhere by @Jon, I have crafted a more general algorithm for extracting named parameters, optional values, and switches.

受@Jon的回答启发,我设计了一个更通用的算法来提取命名参数、可选值和开关。

Let us say that we want to implement a utility foobar. It requires an initial command. It has an optional parameter --foo which takes an optional value (which cannot be another parameter, of course); if the value is missing it defaults to default. It also has an optional parameter --bar which takes a required value. Lastly it can take a flag --baz with no value allowed. Oh, and these parameters can come in any order.

假设我们想要实现一个实用的foobar。它需要一个初始命令。它有一个可选参数——foo它取一个可选值(当然不能是另一个参数);如果值丢失,则默认为默认值。它还有一个可选参数——bar,它接受一个必需的值。最后,它可以取一个标志——baz,不允许有任何值。哦,这些参数可以是任意顺序的。

In other words, it looks like this:

换句话说,它是这样的:

foobar <command> [--foo [<fooval>]] [--bar <barval>] [--baz]

Here is a solution:

这是一个解决方案:

@ECHO OFFSETLOCALREM FooBar parameter demoREM By Garret WilsonSET CMD=%~1IF "%CMD%" == "" (  GOTO usage)SET FOO=SET DEFAULT_FOO=defaultSET BAR=SET BAZ=SHIFT:argsSET PARAM=%~1SET ARG=%~2IF "%PARAM%" == "--foo" (  SHIFT  IF NOT "%ARG%" == "" (    IF NOT "%ARG:~0,2%" == "--" (      SET FOO=%ARG%      SHIFT    ) ELSE (      SET FOO=%DEFAULT_FOO%    )  ) ELSE (    SET FOO=%DEFAULT_FOO%  )) ELSE IF "%PARAM%" == "--bar" (  SHIFT  IF NOT "%ARG%" == "" (    SET BAR=%ARG%    SHIFT  ) ELSE (    ECHO Missing bar value. 1>&2    ECHO:    GOTO usage  )) ELSE IF "%PARAM%" == "--baz" (  SHIFT  SET BAZ=true) ELSE IF "%PARAM%" == "" (  GOTO endargs) ELSE (  ECHO Unrecognized option %1. 1>&2  ECHO:  GOTO usage)GOTO args:endargsECHO Command: %CMD%IF NOT "%FOO%" == "" (  ECHO Foo: %FOO%)IF NOT "%BAR%" == "" (  ECHO Bar: %BAR%)IF "%BAZ%" == "true" (  ECHO Baz)REM TODO do something with FOO, BAR, and/or BAZGOTO :eof:usageECHO FooBarECHO Usage: foobar ^<command^> [--foo [^<fooval^>]] [--bar ^<barval^>] [--baz]EXIT /B 1
  • Use SETLOCAL so that the variables don't escape into the calling environment.
  • 使用SETLOCAL,使变量不会转义到调用环境中。
  • Don't forget to initialize the variables SET FOO=, etc. in case someone defined them in the calling environment.
  • 不要忘记初始化变量SET FOO=等,以防有人在调用环境中定义它们。
  • Use %~1 to remove quotes.
  • 使用%~1删除引号。
  • Use IF "%ARG%" == "" and not IF [%ARG%] == [] because [ and ] don't play will at all with values ending in a space.
  • 使用IF "%ARG%" = ",而不使用IF [%ARG%] =[],因为[和]不会播放,值以空格结尾。
  • Even if you SHIFT inside an IF block, the current args such as %~1 don't get updated because they are determined when the IF is parsed. You could use %~1 and %~2 inside the IF block, but it would be confusing because you had a SHIFT. You could put the SHIFT at the end of the block for clarity, but that might get lost and/or confuse people as well. So "capturing" %~1 and %~1 outside the block seems best.
  • 即使在if块中移动,当前的args(如%~1)也不会被更新,因为它们是在解析if时确定的。您可以在IF块中使用%~1和%~2,但是这会让您感到困惑,因为您有一个移位。你可以在代码块的末尾进行转换以获得清晰性,但是这可能会丢失或者迷惑人。因此,在块外“捕获”%~1和%~1似乎是最好的。
  • You don't want to use a parameter in place of another parameter's optional value, so you have to check IF NOT "%ARG:~0,2%" == "--".
  • 您不希望使用一个参数代替另一个参数的可选值,因此您必须检查是否“%ARG:~0,2%”=“-”。
  • Be careful only to SHIFT when you use one of the parameters.
  • 只有在使用其中一个参数时才要小心移位。
  • The duplicate code SET FOO=%DEFAULT_FOO% is regrettable, but the alternative would be to add an IF "%FOO%" == "" SET FOO=%DEFAULT_FOO% outside the IF NOT "%ARG%" == "" block. However because this is still inside the IF "%PARAM%" == "--foo" block, the %FOO% value would have been evaluated and set before you ever entered the block, so you would never detect that both the --foo parameter was present and also that the %FOO% value was missing.
  • 重复的代码设置FOO=%DEFAULT_FOO%是令人遗憾的,但是另一种选择是在IF“%FOO%”= " SET FOO=%DEFAULT_FOO =%DEFAULT_FOO%不在IF“%ARG%”=“”块外面添加一个IF“%FOO% FOO%”=“”。但是,因为它仍然在IF“%PARAM%”=“-foo”块中,所以在您进入该块之前,% foo %的值将被计算和设置,所以您永远不会检测到-foo参数都存在,而且% foo %的值也丢失了。
  • Note that ECHO Missing bar value. 1>&2 sends the error message to stderr.
  • 注意,回波缺少bar值。>和2向stderr发送错误消息。
  • Want a blank line in a Windows batch file? You gotta use ECHO: or one of the variations.
  • 想要Windows批处理文件中的空行吗?你必须使用ECHO:或者其中的一个变体。