Windows Batch Scripting - Counting Gigabytes
It got me thinking for a really long time. Finally I decided to use the advantage of Windows variables: they are text and number at the same time! What If I just cut the end off as a string? It was working, the assignment was done, everyone was happy.
Fortunately no one else knew about the only flaw of this method: converting means division by 1024 and not by 1000 in IT. For example, 1 TB is 1099511627776 bytes. If you cut only the last 9 characters, you'll get 1099 instead of 1024. That's 75 GB difference, which is above 7% accuracy!!! I was not happy with that. The good news is that the values can be handled as numbers already if they are in "Gigabytes". So I went back to experimenting, and I found out that the result can be greatly improved, if we reduce the 1/15 size from the size:
The code I finally come up with is:
FOR /F "tokens=1-4 delims= " %%a IN ('DIR "%~1\*.*" /-C /S 2^>nul ^| FIND /I "file(s)"') DO SET TOT=%%c
IF !TOT! LSS 1000000000 SET TOT=0000000000
SET /A TOT=!TOT!-(!TOT! / 15)
SET /A TOTAL=%TOTAL%+!TOT!
It's a batch function (which needs EnableDelayedExpansion), what you can call any time. It increases the %TOTAL% variable with the amount of gigabytes used by the folder specified as the only parameter.