I think this is the part where there's an error. This code fragment is inside a for loop FYi.
set /a Used=%Size% - %Free%
set /a Percentage=100 * %Used% / %Size%
how do I implement this arithmetic equation?
Thank you very much!
I think this is the part where there's an error. This code fragment is inside a for loop FYi.
set /a Used=%Size% - %Free%
set /a Percentage=100 * %Used% / %Size%
how do I implement this arithmetic equation?
Thank you very much!
As others have said, one solution to your problem is delayed expansion.
Your actual code must look something like:
for ... in (...) do (
set size=...
set free=...
set /a Used=%Size% - %Free%
set /a Percentage=100 * %Used% / %Size%
)
The problem is %size%
, %free%
, and %used%
are expanded when the line is parsed, and the entire for loop (also, any parenthesized block) is parsed in one pass, before the loop is executed. So they expand to the value that existed before the loop is executed, probably empty in your case.
One solution is to use delayed expansion, which takes place at execution time. Delayed expansion must be enabled before it is used.
setlocal enableDelayedExpansion
for ... in (...) do (
set size=...
set free=...
set /a Used=!Size! - !Free!
set /a Percentage=100 * !Used! / !Size!
)
But that is not necessary if you are simply doing SET /A computations because the SET /A command knows how to expand variables without you doing it. Also, multiple computations can be concatenated on one line with a comma in between. Note that the automatic expansion and concatenated assignments only work with the /A option.
for ... in (...) do (
set size=...
set free=...
set /a "Used=Size-Free, Percentage=100*Used/Size"
)
You still have a potential problem in that batch only supports integer numbers. The fractional portion will be truncated. But you might want to round the fractional portion up. For example, a percentage of 45.7 would be reported as 45, but you might want to round it up to 46. The following formula can be used to get properly rounded integral percents:
set /a "Used=Size-Free, Percentage=(1000*Used/Size+5)/10"
Please send with the for loop, the problem seems to come from it. The code you sent doesn't have any problem. But I have a idea about what it is:
1 Missing Operand
means: one of the equation's operands is missing
2 Now you know it: one of the variables is empty
3 Unset the @echo off
, removing it. So you can see where the value got lost
4 don't forget to pause
TIP: sometimes the for loop gets a empty line...