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

下面是命令行的样子:

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

当前回答

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

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


@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
 

其他回答

让我们保持简单。

下面是.cmd文件。

@echo off
rem this file is named echo_3params.cmd
echo %1
echo %2
echo %3
set v1=%1
set v2=%2
set v3=%3
echo v1 equals %v1%
echo v2 equals %v2%
echo v3 equals %v3%

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

C:\Users\joeco>echo_3params 1abc 2 def  3 ghi
1abc
2
def
v1 equals 1abc
v2 equals 2
v3 equals def

C:\Users\joeco>echo_3params 1abc "2 def"  "3 ghi"
1abc
"2 def"
"3 ghi"
v1 equals 1abc
v2 equals "2 def"
v3 equals "3 ghi"

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

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

这个循环遍历批处理参数(%*),不管它们是否带引号,然后回显每个参数。

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

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是当前目录路径。

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

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

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

每个人的回答都很复杂,但实际上很简单。%1 %2 %3等是解析到文件的参数。%1是参数1,%2是参数2,以此类推。

所以,如果我有一个bat脚本包含这个:

@echo off
echo %1

当我运行批处理脚本时,我输入这个:

C:> script.bat Hello

脚本将简单地输出:

Hello

这对于脚本中的某些变量非常有用,比如名字和年龄。如果我有一个这样的脚本:

@echo off
echo Your name is: %1
echo Your age is: %2

当我输入这个:

C:> script.bat Oliver 1000

我得到这样的输出:

Your name is: Oliver
Your age is: 1000

如果你想智能地处理缺失的参数,你可以这样做:

IF %1.==. GOTO No1
IF %2.==. GOTO No2
... do stuff...
GOTO End1

:No1
  ECHO No param 1
GOTO End1
:No2
  ECHO No param 2
GOTO End1

:End1