MadsTheMan
MadsTheMan

Reputation: 703

How can I make sure its enough disk space in batch?

Does anyone know if its possible to make sure the disk has enough space on a server with batch?

I have a batch script that loops and in this I would like to add a part that makes sure there is enough space on the disk and gives me an message if its not. Like this, easily explained:

Check diskspace
 If below 10mb free space
  echo low diskspace (& probably delete temp files or something)
   else continue

Thanks for any help!

Upvotes: 0

Views: 1122

Answers (1)

MC ND
MC ND

Reputation: 70923

This uses the output of the dir command to retrieve the free space. All the test is wapped inside a subroutine that receives as argument the "drive" to check and the number of bytes required. On exit it raises errorlevel when there is no enough free space.

Arithmetic in batch files is limited 2^31 signed integers, so to handle values greater than 2147483647 and operate with storage units over 2GB more code is required. To avoid this, all the information is indicated/retrieved in bytes, padded and compared as strings.

@echo off
    setlocal enableextensions disabledelayedexpansion

    call :checkFreeSpace d: 123456789 && echo OK || echo No space

    call :checkFreeSpace "\\10.0.0.1\c$" 2000000000
    if errorlevel 1 (
        echo No space
    ) else (
        echo OK
    )

    goto :eof

:checkFreeSpace drive spaceRequired
    setlocal enableextensions disabledelayedexpansion
    set "pad=0000000000000000000000000"
    set "required=%pad%%~2"
    for %%d in ("%~1\.") do for /f "tokens=3" %%a in ('
        dir /a /-c "%%~fd" 2^>nul ^| findstr /b /l /c:"  " 
    ') do set "freeSpace=%pad%%%a"
    if "%freeSpace:~-25%" geq "%required:~-25%" exit /b 0
    exit /b 1

note: This method has one caveat. If the indicated target is a drive root and there is not any file/folder in it, the dir command will not found anything to list and the free space will not be included in its output, making the test fail as the free space will be 0

Upvotes: 1

Related Questions