为什么我的批处理文件回显数组名称和数字而不是字符串? [英] Why does my batch file echo the array name and number instead of the string?
问题描述
我在这里有这段代码,只是试图创建一个从随机数组中选择名称的文件.为什么输出不正确?
I have this code here simply trying to create a file that the name is chosen from a randomized array. Why does it output incorrectly?
代码:
@echo off
set i=0
for %%a in (Cow Dog Bird Fish Meerkat Cat) do (
set /A i+=1
set operator[!i!]=%%a
)
set /a operator=%random%%%4+1
set operator=!operator[%operator%]!
copy /y NUL %operator%>NUL
创建的文件的标题类似于!operator [3]!
,而不是数组中的字符串之一.为什么会这样呢?感谢您的帮助!
The file created is titled something like !operator[3]!
instead of one of the strings in the array. Why is this the case? Any help is appreciated!
推荐答案
Alex K在他的注释中指出了您的主要问题-您丢失了 setlocal enableDelayedExpansion
.
Alex K identified your primary problem in his comment - you are missing setlocal enableDelayedExpansion
.
但是您还有另一个问题-您的数组包含6个值,但是您正在随机选择1到4之间的索引,而不是1到6之间的索引.
But you have another problem - your array contains 6 values, but you are randomly selecting an index between 1 and 4 instead of between 1 and 6.
您应该使用 set/a operator =%random %%% i + 1
.请注意,与SET/A一起使用时,不需要扩展真实的环境变量.
You should use set /a operator=%random%%%i+1
. Note that true environment variables do not need to be expanded when used with SET /A.
这篇关于为什么我的批处理文件回显数组名称和数字而不是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!