I wrote this script to looking for volume with enough free space:
@echo on
setlocal
set gbsize=1,073,741,824
Set gbsize=%gbsize:,=%
for %%A in (A B C D) do
Use
setlocal enabledelayedexpansion
instead of just setlocal
and then use !bytesfree!
to refer to the variable (just replace %
by !
).
This is because cmd
expands variables as it parses a command, not when the command is run (which, obviously happens after parsing). A command in this case could also be a complete for
statement including the block after it. So all instances of %bytesfree%
within the loop are replaced by their value before the loop, which happens to be an empty string.
Delayed expansion is a special form of variable expansion which expands variables when a command is run instead of when parsing it. It can be enabled with
setlocal enabledelayedexpansion
(within a batch file) or
cmd /v:on
(for a complete session, but not in a batch file, unless you don't want it to resume).
Then the syntax !bytesfree!
is used to refer to variables which are then expanded just prior to running a command. So when setting and using the same variable within a block (for
loop, if
, etc.) you pretty much always want to use delayed expansion.