Windows – Get disk/partition size in batch file

batchdisk-spacewindowswindows 7

How to get total size of a disk or partition(a USB hard drive with 1 NTFS partition) in a batch file?
I would rather not go for logic that go over files recursively(the ones with for /f) since it's a 1TB drive and it may take a long time to determine size.

I am open to use some small third party tool which will return size to batch file.

PS: I am on Windows 7 x64 Ultimate

Best Answer

There is probably an easier way to do this, but here is what I use

If all you want is the bytes, you can just do this command change T to the drive letter of your external (for a one liner at command prompt change %% to % and set space= to echo)

for /f "tokens=3 delims= " %%a in ('dir /-c T: ^| find "bytes free"') do set space=%%a

if you want to then take that and simplfy it, first set guidelines for each size

set divide=1073741824&&set size=gigabytes
if %space% lss 1073741824 set divide=1048576&&set size=megabytes
if %space% lss 1048576 set divide=1024&&set size=kilobytes
if %space% lss 1024 set divide=1&&set size=bytes

Then write a temporary VBS script as batch can't handle the math

echo wsh.echo cdbl(%space%)/%divide% > %temp%\tmp.vbs

Run it, capture result and delete it

for /f %%a in ('cscript //nologo %temp%\tmp.vbs') do set space=%%a
del %temp%.\tmp.vbs

Then the following trims the result to two decimal places

for /f "tokens=1,2 delims=." %%a in ("%space%") do (
  set s1=%%a
  set s2=%%b
)
if not "%s2%"=="" (set space=%s1%.%s2:~0,2%) else (set space=%s1%)

Echo results

echo Drive has %space% %size% free.

[EDIT]

For total size, you can use diskpart list volume (change "%%a"=="T" to "%%a"=="driveletterhere")

for /f "tokens=3,6,7 delims= " %%a in ('echo list volume ^| diskpart') do if "%%a"=="T" set size=%%b && set size2=%%c

and bonus how you could calculate that:

if [%size2%]==[TB] (
    set isBigEnough=1
) else if [%size2%]==[GB] (
    if %size% GTR 31 set isBigEnough=1
)
if not defined isBigEnough set isBigEnough=0