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

Jerold Schulman

February 8, 2005

1 Min Read
ITPro Today logo in a gray background | ITPro Today


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 \ComputerNameC$.FreeSpace           is a <a href="https://www.itprotoday.com/article/jsifaq/jsi-tip-5535-how-can-i-cause-a-called-batch-file-to-return-a-call-directed-environment-variable-.aspx">call directed environment variable</a> 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 bytesMB (megabyte) = 1,048,576 bytesGB (gigabyte) = 1,073,741,824 bytesTB (terabyte) = 1,099,511,627,776 bytesPB (petabyte) = 1,125,899,906,842,624 bytesEB (exabyte)  = 1,152,921,504,606,846,976 bytesWhen 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 offsetlocalif {%2}
{} goto :ERRfor /f "tokens=1-3*" %%a in ('dir %1 /-c^|findstr /i /C:"bytes free"') do set FreeSpace=%%cif {%3}
{} goto finishif /i {%3}
{KB} set units=1024&goto divideif /i {%3}
{MB} set units=1048576&goto divideif /i {%3}=={GB} set units=1073741824&goto divide:ERR@echo Syntax Free LOCALorREMOTE_DRIVE FreeSpace Unitsendlocalgoto :EOF:divideset 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%:enddel /q %work%:finishendlocal&set %2=%FreeSpace%



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like