1

I want to write a batch file which gives me free space left in C drive.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Pradeep
  • 3,420
  • 11
  • 35
  • 38
  • 1
    http://stackoverflow.com/questions/293780/free-space-in-a-cmd-shell –  Sep 05 '11 at 07:11

1 Answers1

4

The following script will give you free bytes on the drive:

@setlocal enableextensions enabledelayedexpansion
@echo off
for /f "tokens=3" %%a in ('dir c:\') do (
    set bytesfree=%%a
)
set bytesfree=%bytesfree:,=%
echo %bytesfree%
endlocal && set bytesfree=%bytesfree%

Note that this depends on the output of your dir command, which needs the last line containing the free space of the format 24 Dir(s) 34,071,691,264 bytes free. Specifically:

  • it must be the last line (or you can modify the for loop to detect the line explicitly rather than relying on setting bytesfree for every line).
  • the free space must be the third "word" (or you can change the tokens= bit to get a different word).
  • thousands separators are the , character (or you can change the substitution from comma to something else).

It doesn't pollute your environment namespace, setting only the bytesfree variable on exit. If your dir output is different (eg, different locale or language settings), you will need to adjust the script.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • I had to use the output from this script and build an `if` expression to determine if I had to delete old files off a drive. I used: `ECHO %bytesfree%>x&FOR %%? IN (x) DO SET /A strlen=%%~z? - 2&del x *newline* IF %strlen% LEQ 13 [...]` – Aaron Gillion Jan 14 '16 at 03:10