How can I check the size of a file in a Windows batch script?

Solution 1:

If the file name is used as a parameter to the batch file, all you need is %~z1 (1 means first parameter)

If the file name is not a parameter, you can do something like:

@echo off
setlocal
set file="test.cmd"
set maxbytesize=1000

FOR /F "usebackq" %%A IN ('%file%') DO set size=%%~zA

if %size% LSS %maxbytesize% (
    echo.File is ^< %maxbytesize% bytes
) ELSE (
    echo.File is ^>= %maxbytesize% bytes
)

Solution 2:

I like @Anders answer because the explanation of the %~z1 secret sauce. However, as pointed out, that only works when the filename is passed as the first parameter to the batch file.

@Anders worked around this by using FOR, which, is a great 1-liner fix to the problem, but, it's somewhat harder to read.

Instead, we can go back to a simpler answer with %~z1 by using CALL. If you have a filename stored in an environment variable it will become %1 if you use it as a parameter to a routine in your batch file:

@echo off
setlocal
set file=test.cmd
set maxbytesize=1000

call :setsize %file%

if %size% lss %maxbytesize% (
    echo File is less than %maxbytesize% bytes
) else (
    echo File is greater than or equal %maxbytesize% bytes
)
goto :eof

:setsize
set size=%~z1
goto :eof

I've been curious about J. Bouvrie's concern regarding 32-bit limitations. It appears he is talking about an issue with using LSS not on the filesize logic itself. To deal with J. Bouvrie's concern, I've rewritten the solution to use a padded string comparison:

@echo on
setlocal
set file=test.cmd
set maxbytesize=1000

call :setsize %file%

set checksize=00000000000000000000%size%
set checkmaxbytesize=00000000000000000000%maxbytesize%
if "%checksize:~-20%" lss "%checkmaxbytesize:~-20%" (
    echo File is less than %maxbytesize% bytes
) else (
    echo File is greater than or equal %maxbytesize% bytes
)
goto :eof

:setsize
set size=%~z1
goto :eof

Solution 3:

%~z1 expands to the size of the first argument to the batch file. See

C:\> call /?

and

C:\> if /?

Simple example:

@ECHO OFF
SET SIZELIMIT=1000
SET FILESIZE=%~z1

IF %FILESIZE% GTR %SIZELIMIT% Goto No

ECHO Great! Your filesize is smaller than %SIZELIMIT% kbytes.
PAUSE
GOTO :EOF

:No
ECHO Um ... You have a big filesize.
PAUSE
GOTO :EOF