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 (*
on my system I have to write
set checker=Random
instead of
set checker=!Random!
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).