Windows Batch Scripting - Counting Gigabytes

command prompt.png
Recently I was assigned to a task where I had to collect folder sizes (and do some math with them) on large number of servers. Talking about real file servers I quickly met the famous "Invalid number.  Numbers are limited to 32-bits of precision." message. Here's how I solved it.

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 TOT=!TOT:~0,-9!
SET /A TOT=!TOT!-(!TOT! / 15)
GOTO :eof

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.

Enjoy! :)

Add a comment

HTML code is displayed as text and web addresses are automatically converted.

This post's comments feed