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