在命令提示符中使用 FOR 循环通过 SET 构建环境变量
我在使用以下命令提示符命令时遇到问题(在 Windows XP 中)。
set SOMEVAR=
for /F %i in (1 2 3) do set SOMEVAR=%SOMEVAR% "%i"
echo %SOMEVAR%
我希望它构建 SOMEVAR 变量,以便它包含 for 循环中引号中的每个项目,并用空格分隔: 1 2 3
但是这是什么我反而得到了。
> set SOMEVAR=
> for /F %i in (1 2 3) do set SOMEVAR=%SOMEVAR% "%i"
>set SOMEVAR=%SOMEVAR% "1"
>set SOMEVAR=%SOMEVAR% "2"
>set SOMEVAR=%SOMEVAR% "3"
> echo %SOMEVAR%
%SOMEVAR% "3"
看起来环境变量在 FOR 循环期间没有更新和/或扩展。
有什么想法如何使用 FOR 循环构建环境变量吗?
我当前使用的解决方法是让 FOR 循环调用 BAT 文件中的本地标签,该文件 SET 将变量设置为自身加上 %1< /strong>,然后跳转到:EOF。它有效,但我想弄清楚是否有一种方法可以让它在一行中工作,而无需调用和标签开销。
I am having trouble with the following command prompt commands (in Windows XP).
set SOMEVAR=
for /F %i in (1 2 3) do set SOMEVAR=%SOMEVAR% "%i"
echo %SOMEVAR%
I expect it to build the SOMEVAR variable so that it contains each item in the for loop in quotes, separated by a space: 1 2 3
However what this is what I get instead.
> set SOMEVAR=
> for /F %i in (1 2 3) do set SOMEVAR=%SOMEVAR% "%i"
>set SOMEVAR=%SOMEVAR% "1"
>set SOMEVAR=%SOMEVAR% "2"
>set SOMEVAR=%SOMEVAR% "3"
> echo %SOMEVAR%
%SOMEVAR% "3"
It looks like environment variables are not updated and/or expanded during a FOR loop.
Any ideas how to build an environment variable with a FOR loop?
A workaround that I’m currently using is to have the FOR loop call a local label in the BAT file which SETs the variable to itself plus %1, then jumps to :EOF. It works, but I’d like to figure out if there is a way to get it to work in one line without the call and label overhead.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须启用它的一个选项
将解释
哎呀,我的意思是
一定要从头到尾阅读
编辑:事实证明,您可以在单独的批处理文件中打开它。
将此文本另存为 temp.bat
its an option you have to enable
will explain
oops, i meant
be sure to read all the way to the bottom
Edit: it turns out that you can turn this on in an individual a batch file.
save this text as temp.bat
中已有的 vbscript
这是一个等效的替代方案,使用系统输出
C:\test>cscript //nologo test.vbs
123
另外,如果您要使用大量这些东西,您可以利用 vbscript 的字典集合或数组来存储变量。
here's an equivalent alternative, using vbscript which is already on your system
output
C:\test>cscript //nologo test.vbs
123
Plus, if you are going to use a lot of these stuff, you can make use of vbscript's dictionary collection or arrays to store your variables.