Windows 仅使用一个参数或另一个参数&;批量使用指定的文件

Windows 仅使用一个参数或另一个参数&;批量使用指定的文件,windows,batch-file,cmd,parameters,scripting,Windows,Batch File,Cmd,Parameters,Scripting,我想用批处理脚本做两件事 第一个是仅使用一个参数或另一个参数。即,以下各项: C:\> foo.bat file.txt /A /A commands here. C:\> foo.bat file.txt /B /B commands here. C:\> foo.bat file.txt /A /B ERROR: Either /A or /B can be specified only. C:\> foo.bat file.txt /B /A ERROR: E

我想用批处理脚本做两件事

第一个是仅使用一个参数或另一个参数。即,以下各项:

C:\> foo.bat file.txt /A
/A commands here.

C:\> foo.bat file.txt /B
/B commands here.

C:\> foo.bat file.txt /A /B
ERROR: Either /A or /B can be specified only.

C:\> foo.bat file.txt /B /A
ERROR: Either /A or /B can be specified only.
C:\> bar.bat file.txt /A
file.txt has been archived.
第二种是使用指定的文件执行命令。即:

C:\> foo.bat file.txt /A
/A commands here.

C:\> foo.bat file.txt /B
/B commands here.

C:\> foo.bat file.txt /A /B
ERROR: Either /A or /B can be specified only.

C:\> foo.bat file.txt /B /A
ERROR: Either /A or /B can be specified only.
C:\> bar.bat file.txt /A
file.txt has been archived.
我确实试图写一些代码来实现这一点,但我没有走得太远。以下是我迄今为止的工作:

if /i [%~f1] == [FILE] set usedfile=[FILE]
if /i [%1] == [] goto error
if /i [%2] == [/A] set "A_or_B=A"
if /i [%2] == [/B] set "A_or_B=B"

然后%usedfile%将通过
copy

被复制到另一个位置。看起来第一个参数应该是文件名,但我不太确定。这会让你更接近

C:>TYPE asdf.bat
@ECHO OFF
SETLOCAL
SET EXITCODE=0

if /i [%~f1] == [FILE] set usedfile=[FILE]
if /i [%1] NEQ [] (SET "usedfile=%~1" & GOTO NextSwitch)
ECHO ERROR: File not specified.
SET EXITCODE=1
GOTO TheEnd

SET "OPT_A="
SET "OPT_B="
:NextSwitch
IF [%2] EQU [] (GOTO SwitchesDone)
if /i [%2] == [/A] (
    IF [%OPT_B%] NEQ [true] (SET "OPT_A=true") ELSE (GOTO SwitchError)
)
if /i [%2] == [/B] (
    IF [%OPT_A%] NEQ [true] (SET "OPT_B=true") ELSE (GOTO SwitchError)
)
if /i [%2] == [/B] set "OPT_B=true"
SHIFT
GOTO NextSwitch

:SwitchError
ECHO ERROR: Either /A or /B can be specified only.
SET EXITCODE=2
GOTO TheEnd

:SwitchesDone
ECHO NB: usedfile is %usedfile%
ECHO NB: OPT_A is %OPT_A%
ECHO NB: OPT_B is %OPT_B%

:TheEnd
EXIT /B %EXITCODE%
这里有几次跑步

21:30:52.27  C:\src\t
C:>asdf.bat adsf /B /A
ERROR: Either /A or /B can be specified only.

21:31:01.01  C:\src\t
C:>asdf.bat adsf /A
NB: usedfile is adsf
NB: OPT_A is true
NB: OPT_B is

如果您甚至不确定如何启动,请阅读(并遵循)。这将需要编写cmd脚本(.bat文件)代码。通过在PowerShell中使用参数集,您可以免费获得互斥。感谢您的帮助。所以我更进一步了。到目前为止,我已将代码添加到原始问题中。是的,第一个参数必须是有效文件。我还没有完全阅读过代码,但我确实试过了,它看起来像预期的那样工作!我会在可能的时候汇报我的结果。