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 (
for /f "tokens=3,4,5,*" %%B in ('dir %%A:\') do (
set bytesfree=%%B
set bytesfree=%bytesfree:,=%
if %%D == free If %bytesfree% gtr %gbsize% echo hi
)
)
My problem is that the bytesfree variable dosent save its value. the output is(echo is on)
C:\Users\Desktop>(
set bytesfree=**780,607,488**
set bytesfree=**23167987712**
if free == free If 23167987712 GTR 1073741824 echo hi
)
hi
looks like the bytesfree losed its value.
Can anyone please help? and provide some explantation?
thanks.
Short answer:
Use
instead of just
setlocaland then use!bytesfree!to refer to the variable (just replace%by!).Longer answer:
This is because
cmdexpands 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 completeforstatement 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
(within a batch file) or
(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 (forloop,if, etc.) you pretty much always want to use delayed expansion.