42

我有一个带有多个参数的批处理脚本。我正在读取它们的总数,然后像这样运行一个 for 循环:

@echo off
setlocal enabledelayedexpansion

set argCount=0
for %%x in (%*) do set /A argCount+=1
echo Number of processed arguments: %argCount%

set /a counter=0
for /l %%x in (1, 1, %argCount%) do (
set /a counter=!counter!+1 )

我现在想要做的是使用我的运行变量(xcounter)来访问输入参数。我在想这样的事情:

REM Access to %1 
echo %(!counter!)

在理想的世界中,这条线应该打印出我的第一个命令行参数,但显然它没有。我知道我对操作员做错了什么%,但是无论如何我可以像这样访问我的参数吗?

//编辑:只是为了让事情清楚 - 问题是它%(!counter!)为我提供了变量的值counter。它的含义counter=2给了我2,而不是%2.

4

6 回答 6

69
@echo off
setlocal enabledelayedexpansion

set argCount=0
for %%x in (%*) do (
   set /A argCount+=1
   set "argVec[!argCount!]=%%~x"
)

echo Number of processed arguments: %argCount%

for /L %%i in (1,1,%argCount%) do echo %%i- "!argVec[%%i]!"

例如:

C:> test One "This is | the & second one" Third
Number of processed arguments: 3
1- "One"
2- "This is | the & second one"
3- "Third"

另一个:

C:> test One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve etc...
Number of processed arguments: 13
1- "One"
2- "Two"
3- "Three"
4- "Four"
5- "Five"
6- "Six"
7- "Seven"
8- "Eight"
9- "Nine"
10- "Ten"
11- "Eleven"
12- "Twelve"
13- "etc..."
于 2013-11-07T13:52:20.553 回答
28
:loop
@echo %1
shift
if not "%~1"=="" goto loop
于 2016-09-29T17:27:13.933 回答
13

这是访问第二个(例如)参数的一种方法(可以将其放入for /l循环中,见下文。):

@echo off
setlocal enableDelayedExpansion
set /a counter=2
call echo %%!counter!
endlocal

所以:

setlocal enableDelayedExpansion
set /a counter=0
for /l %%x in (1, 1, %argCount%) do (
 set /a counter=!counter!+1
 call echo %%!counter! 
)
endlocal
于 2013-11-07T12:43:26.320 回答
8

如果要保持代码简短而不是明智,那么

for %%x in (%*) do (
   echo Hey %%~x 
)
于 2016-12-05T12:55:09.413 回答
2
@ECHO OFF
SETLOCAL
SET nparms=0
FOR /l %%i IN (1,1,20) DO (
 SET myparm=%%i
 CALL :setparm %*
 IF DEFINED myparm SET nparms=%%i&CALL ECHO Parameter %%i=%%myparm%%
)
ECHO there were %nparms% parameters in %*
GOTO :EOF

:setparm
IF %myparm%==1 SET myparm=%1&GOTO :EOF
shift&SET /a myparm -=1&GOTO setparm
GOTO :eof

这应该显示如何按位置提取随机参数。

于 2013-11-07T13:31:25.780 回答
2

对于简单的迭代,我们不能只检查代码末尾带有“shift / 1”的附加参数并循环回来吗?这将处理超过 10 个参数,上限未测试。

:loop

:: Your code using %1
echo %1

:: Check for further batch arguments.     
shift /1
IF [%1]==[] (
goto end
) ELSE (
goto loop
)

:end
pause
于 2016-07-15T10:00:21.627 回答