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
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!
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With