user1214135
user1214135

Reputation: 635

Checking Remaining Harddisk Space in a DOS Batch Script. IF Condition not working

I'd like to have a notification that informs me when my hard disk space is getting low. I'm running Windows 7 Professional and I think a quick batch file could handle this. I'll schedule it to run once a day. This is what I have so far:

This finds the remaining disk space using the "dir" command and the "find" command. It stores the value in Var1. (This works for me)

@echo off
FOR /F "tokens=*" %%i in ('dir ^| find "free"') do SET WinVer=%%i 
FOR /F "tokens=1-3 delims=]-" %%A IN ("%WinVer%" ) DO ( 
SET Var1=%%A 
)

This pulls the number from the the result and removes the commas. The result will look like "111222333444" without the quotes: (This works for me)

set Var1=%Var1:~10,15%
set Var1=%Var1:,=%

This checks if the value in Var1 is less than 100 GB (my hypothetical disk space floor). If so, it creates a file called "lowSpace.txt" that I'll see at some point. (This doesn't work for me)

if %Var1% leq 100000000000 dir > lowSpace.txt

This "if" statement is causing me problems. My free disk space is about 150 GB (or 150000000000), so the if condition should fail and the "dir > lowSpace.txt" should not be running, but it does anyway.

Am I comparing my numbers wrong? Or is something wrong with my "if" statement? The code seems to consider 150 GB to be both greater than and less than 100 GB.


Here is my full script:

@echo off
FOR /F "tokens=*" %%i in ('dir ^| find "free"') do SET WinVer=%%i 
FOR /F "tokens=1-3 delims=]-" %%A IN ("%WinVer%" ) DO ( 
SET Var1=%%A 
) 
set Var1=%Var1:~10,15%
set Var1=%Var1:,=%

if %Var1% leq 100000000000 dir > lowSpace.txt
@echo on
@echo %Var1%

Note that 100 GB isn't my real hard disk space floor. I'm just using that number to test my code.

Upvotes: 0

Views: 9452

Answers (2)

bruno777
bruno777

Reputation: 1896

wmic command is sometimes unavailable.

So, in a singleline :

for /F "tokens=8" %%? in ('fsutil volume diskfree C:') do set FREE_SPACE=%%?

Result is in variable %FREE_SPACE% in bytes.

Upvotes: 2

dbenham
dbenham

Reputation: 130839

I asked and answered this very question at Windows batch file IF failure - How can 30000000000000 equal 40000000000?. Your problem is Windows batch cannot handle numbers greater than ~2 GB. If treats any number greater than 2 GB as equal to 2 GB. I posted a simple work around that prefixes the numbers with zeros and forces a string comparison instead of a numeric comparison.

Note, you can also use WMIC to get the free space of any given drive:

for /f "tokens=2" %%S in ('wmic volume get DriveLetter^, FreeSpace ^| findstr "^C:"') do set freeSpace=%%S

Upvotes: 5

Related Questions