Skip navigation

JSI Tip 9035. How can I retrieve the free space of a local or remote drive, using standard commands?


I have scripted Free.bat to return the free space of a local or remote volume. Free.bat uses standard commands.

The syntax for using Free.bat is:

call Free LOCALorREMOTE_DRIVE FreeSpace \[Units\]

Where:

LOCALorREMOTE_DRIVE is the local or remote drive, like C: or D: or X: or \\ComputerName\C$.

FreeSpace           is a call directed environment variable that will contain the number of free space Units.

Units               is an optional parameter that contains KB, MB, or GB. The default is bytes.
NOTE: See the following bytes per unit:
KB (kilobyte) = 1,024 bytes
MB (megabyte) = 1,048,576 bytes
GB (gigabyte) = 1,073,741,824 bytes
TB (terabyte) = 1,099,511,627,776 bytes
PB (petabyte) = 1,125,899,906,842,624 bytes
EB (exabyte)  = 1,152,921,504,606,846,976 bytes

When using units, FreeSpace is rounded to the nearest whole number.
NOTE: FreeSpace is NOT a arithmetic environment variable. If you know that the number does NOT exceed 32 bits of precision, you can make it arithmetic using:
if "%FreeSpace%" EQU "0" (
 set /a FreeSpace=0
 ) ELSE (
 set /a FreeSpace=%FreeSpace%
)
Free.bat contains:
@echo off
setlocal
if \{%2\}

\{\} goto :ERR for /f "tokens=1-3*" %%a in ('dir %1 /-c^|findstr /i /C:"bytes free"') do set FreeSpace=%%c if \{%3\}

\{\} goto finish if /i \{%3\}

\{KB\} set units=1024&goto divide if /i \{%3\}

\{MB\} set units=1048576&goto divide if /i \{%3\}==\{GB\} set units=1073741824&goto divide :ERR @echo Syntax Free LOCALorREMOTE_DRIVE FreeSpace Units endlocal goto :EOF :divide set work="%TEMP%\FreeSpace_%RANDOM%.VBS" @echo Set objArgs = WScript.Arguments>%work% @echo wscript.echo eval(objArgs(0))>>%work% for /f "Tokens=*" %%a in ('cscript //nologo %work% %FreeSpace%/%units%') do ( set xx=%%a ) for /f "Tokens=1* Delims=." %%x in ('@echo %xx%') do ( set FreeSpace=%%x set Remain=%%y0 ) if "%Remain:~0,1%" LSS "5" goto end for /f "Tokens=*" %%a in ('cscript //nologo %work% %FreeSpace%+1') do ( set xx=%%a ) set FreeSpace=%xx% :end del /q %work% :finish endlocal&set %2=%FreeSpace%



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish