随机变量在“for"中没有变化在 Windows 批处理文件中循环 [英] Random variable not changing in "for" loop in windows batch file

查看:30
本文介绍了随机变量在“for"中没有变化在 Windows 批处理文件中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图多次打印出一个随机数,但在我使用的 for 循环中,它没有重置变量.这是我的代码.

I'm trying to print out a Random number multiple times but in the for loop I use, it doesn't reset the variable. Here's my code.

@echo off


for %%i in (*.txt) do (

set checker=%Random%
echo %checker%
echo %%i% >> backupF 

)   


echo Complete

有 5 个文本文件,所以我希望它打印 5 个不同的随机数,但它只打印 5 次相同的随机数.任何帮助将不胜感激.谢谢!

There are 5 text files and so I want it to print 5 different random numbers but it just prints the same random number 5 times. Any help would be greatly appreciated. Thanks!

推荐答案

我不确定您是如何让它打印出一个随机数的.在您的情况下,%checker% 应评估为空字符串,除非您从同一个 cmd 会话中多次运行您的脚本.

I'm not sure how you've been able to have it print even one random number. In your case, %checker% should evaluate to an empty string, unless you run your script more than once from the same cmd session.

基本上,您的脚本没有按预期工作的原因是循环体中的变量在循环执行之前被解析和评估.当主体执行时,变量已经被评估并且在所有迭代中使用相同的值.

Basically, the reason your script doesn't work as intended is because the variables in the loop body are parsed and evaluated before the loop executes. When the body executes, the vars have already been evaluated and the same values are used in all iterations.

因此,您需要的是延迟评估,也称为延迟扩展.您需要先启用它,然后对其使用特殊语法.

What you need, therefore, is a delayed evaluation, otherwise called delayed expansion. You need first to enable it, then use a special syntax for it.

这是您修改后的脚本以使用延迟扩展:

Here's your script modified so as to use the delayed expansion:

@echo off

setlocal EnableDelayedExpansion

for %%i in (*.txt) do (

set checker=!Random!
echo !checker!
echo %%i% >> backupF

)

endlocal

echo Complete

如您所见,setlocal EnableDelayedExpansion 启用对延迟扩展语法的特殊处理,即在变量名称周围使用 !s 而不是 %>s.

As you can see, setlocal EnableDelayedExpansion enables special processing for the delayed expansion syntax, which is !s around the variable names instead of %s.

您仍然可以使用立即扩展(使用 %),它可以正常工作(基本上,在括号中的命令块之外).

You can still use immediate expansion (using %) where it can work correctly (basically, outside the bracketed command blocks).

这篇关于随机变量在“for"中没有变化在 Windows 批处理文件中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆