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

下面是命令行的样子:

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

当前回答

成对的参数

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

@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

其他回答

没有必要把事情复杂化。例如,它只是命令%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参数。

我是这样做的:

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

下面是命令的样子:

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

%1应用于第一个参数,%2(这是棘手的部分)应用于第二个参数。您最多可以通过这种方式传递9个参数。

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

echo off
set arg1=%1
set arg2=%2
shift
shift
fake-command /u %arg1% /p %arg2% %*

跑步时:

test-command admin password foo bar

上面的批处理文件将运行:

fake-command /u admin /p password admin password foo bar

我的语法可能有点错误,但这是大意。

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

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