批处理脚本 - 遍历参数 [英] Batch-Script - Iterate through arguments
问题描述
我有一个带有多个参数的批处理脚本.我正在读取它们的总数,然后像这样运行 for 循环:
I have a batch-script with multiple arguments. I am reading the total count of them and then run a for loop like this:
@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 )
我现在想要做的是使用我的运行变量(x
或 counter
)来访问输入参数.我在想类似这样的事情:
What I want to do now, is to use my running variable (x
or counter
) to access the input arguments. I am thinking aobut something like this:
REM Access to %1
echo %(!counter!)
在理想的世界中,这一行应该打印出我的第一个命令行参数,但显然它没有.我知道我在使用 %
运算符时做错了什么,但是无论如何我可以像这样访问我的参数吗?
In an ideal world this line should print out my first command line argument but obviously it doesn't. I know I am doing something wrong with the %
operator, but is there anyway I could access my arguments like this?
//edit: 澄清一下——问题是 %(!counter!)
为我提供了变量 counter
的值.counter=2
的含义它给了我 2
而不是 %2
的内容.
//edit: Just to make things clear - the problem is that %(!counter!)
provides me with the value of the variable counter
. Meaning for counter=2
it gives me 2
and not the content of %2
.
推荐答案
这是访问第二个(例如)参数的一种方法(这可以放在 for/l
循环中,见下文.):
here's one way to access the second (e.g.) argument (this can be put in a for /l
loop, see below.):
@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
这篇关于批处理脚本 - 遍历参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!