批处理语言中的 For 循环

For Loop in batch language

所以我有一个看起来像这样的 CSV 文件:

ComputerName,UserID,192.168.0.xx
ComputerName,UserID,192.168.0.xx

我正在尝试编写一个批处理循环脚本,它将读取脚本中的 IP 并对它们执行 ping 操作,这是我目前所拥有的:

setlocal Disable DelayedExpansion

for /f "tokens=1,2,3 delims=" %%a in (test.csv) do(

Set line=%%c
ping %line%

)

设置变量有效,但似乎我无法从批处理文件中读取任何内容,因为我收到了一条错误消息:

%%a was unexpected at this time 

我想知道我怎样才能解决这个问题或者我做错了什么

delims= 位表示没有分隔符,因此整个字符串被视为一个完整的行,而不是像您希望的那样在逗号上拆分。改成

setlocal EnableDelayedExpansion

for /f "tokens=1,2,3 delims=," %%a in (test.csv) do (
    Set line=%%c
    ping !line!
)

有一些问题,但你已经很接近了。我已经更新了您的脚本并注意到了更正。

REM You want to _Enable_ delayed expansion. This is a single word.
setlocal EnableDelayedExpansion

REM Your delimiter needs to be a ,
for /f "tokens=1,2,3 delims=," %%a in (test.csv) do (
    Set line=%%c
    REM You need to access the line value enclosed in !'s since it is delayed expansion.
    ping !line!
)

或者,您可以在命令提示符下以单行方式执行此操作(不需要批处理文件):

FOR /F "tokens=1,2,3 delims=," %a in (test.csv) do PING %c