随机变量不改变"为"循环在windows批处理文件 [英] Random variable not changing in "for" loop in windows batch file

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

问题描述

我想一个随机数多次打印出来,但在for循环我用,它不重置变量。这里是我的code。

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倍。任何帮助将大大AP preciated。谢谢!

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!

推荐答案

我不知道你是如何能够把它打印连一个随机数。在你的情况,%检查%应该评估为空字符串,除非你运行你的脚本不是从同一次 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左右变量名,而不是秒。

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).

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

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