我需要在运行批处理文件时传递一个ID和密码,而不是将它们硬编码到文件中。
下面是命令行的样子:
test.cmd admin P@55w0rd > test-log.txt
我需要在运行批处理文件时传递一个ID和密码,而不是将它们硬编码到文件中。
下面是命令行的样子:
test.cmd admin P@55w0rd > test-log.txt
当前回答
创建一个新的批处理文件(例如:openclass.bat),并在文件中写入这一行:
java %~n1
然后将批处理文件放在system32文件夹中,找到你的Java类文件,右键单击,Properties, Open with…,然后找到你的批处理文件,选择它,这就是…
这对我很管用。
PS:当我关闭Java类时,我找不到关闭cmd窗口的方法。现在……
其他回答
我是这样做的:
@fake-command /u %1 /p %2
下面是命令的样子:
test.cmd admin P@55w0rd > test-log.txt
%1应用于第一个参数,%2(这是棘手的部分)应用于第二个参数。您最多可以通过这种方式传递9个参数。
要在命令行中引用一个set变量,你需要使用%a%,例如:
set a=100
echo %a%
rem output = 100
注意:这适用于Windows 7 pro。
成对的参数
如果你喜欢在键值对中传递参数,你可以使用这样的方法:
@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
让我们保持简单。
下面是.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>
另一个有用的技巧是使用%*表示“所有”。例如:
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
我的语法可能有点错误,但这是大意。