Windows – Determine if C drive has 2 GB of free disk space

batchdisk-space-utilizationhard drivewindowswindows-command-prompt

I am trying to determine if a target pc has atleast 2 GB of free space. Here is what I have so far:

@echo off
for /f "usebackq delims== tokens=2" %%x in (`wmic logicaldisk where "DeviceID='C:'" get FreeSpace /format:value`) do set "FreeSpace=%%x"
IF /i %FreeSpace% GTR "2147483648" (ECHO C Drive Has Enough Available Disk For Install %FreeSpace%) else (ECHO C Drive Is FULL %FreeSpace%)

It does not matter if I set 2 GB or change it to 200 GB it always says I have enough space even though this drive only has 90 GB…Please help if you can.

this question was what I based my above code on:
Check free disk space using Batch commands

seems like it should work but it does not.

Best Answer

You have 2 problems with your code:

1) IF only does a numeric comparison if the string on both sides evaluates to a number. Your left side is numeric, but your right side has quotes, which forces the entire comparison to be done using string semantics. Numeric digits always sort higher than a quote character, so it always reports TRUE.

As austinian suggests in his answer, removing the quotes apparantly gives the correct answer in your case. But that is not the entire story! In reality it is checking if the free space is greater than or equal to 2147483647.

2) Windows batch (cmd.exe) numbers are limited to signed 32 bit precision, which equates to a max value of 2 GB -1 byte (2147483647). The IF statement has an odd (perhaps unfortunate) behavior that any number greater than 2147483647 is treated as equal to 2147483647. So you cannot use your technique to test free space for values greater than 2147483647.

See https://stackoverflow.com/q/9116365/1012053 for more information.

Described in the link's answer is a tecnique you can use to test large numbers. You must left pad both sides of the condition to the same width, and force a string comparison.

For example, The following will test if free space is >= 4294967296 (4 GB)

@echo off
setlocal
set "pad=000000000000000"
set "NeededSpace=%pad%4294967296"
for /f "delims== tokens=2" %%x in (
  'wmic logicaldisk where "DeviceID='C:'" get FreeSpace /format:value'
) do for %%y in (%%x) do set "FreeSpace=%pad%%%y"
if "%FreeSpace:~-15%" geq "%NeededSpace:~-15%" echo Drive has at least 4 GB free space.