I'm trying to retrieve the size of two files to compare the size of eachothers. The problem is, one of the two files contain a space in his path, the code is like that :
SET pathToFile1="C:\Program Files\file1ToCompare"
SET pathToFile2="C:\Users\file2ToCompare"
FOR /F "usebackq" %%A ('%pathToFile1%') DO SET file1Size=%%~zA
FOR /F "usebackq" %%B ('%pathToFile2%') DO SET file2Size=%%~zB
IF %file1Size% LSS %file2Size% (
:: do things
)
The size of the second file is correctly set, but the size of the first file is not retrieved... I've been searching an answer for a day now, but can't find any one (maybe i'm not searching correctly, sorry in this case)
Do you have an idea to get the size of the first file ?
Do not use option /F
which is for parsing one or more strings read from a file or specified directly or read from captured output of a command executed in a separate command process in background.
Use just command FOR without any option to process the specified file.
SET "pathToFile1=C:\Program Files\file1ToCompare"
SET "pathToFile2=C:\Users\file2ToCompare"
IF NOT EXIST "%pathToFile1%" GOTO :EOF
IF NOT EXIST "%pathToFile2%" GOTO :EOF
FOR %%A IN ("%pathToFile1%") DO SET "file1Size=%%~zA"
FOR %%B IN ("%pathToFile2%") DO SET "file2Size=%%~zB"
IF %file1Size% LSS %file2Size% (
rem do things
)
Read answer on How to set environment variables with spaces? why it is better to use the syntax set "variable=value"
and enclose the entire string including one or more environment variable references in double quotes.
Read next answer on Where does GOTO :EOF return to? The two IF commands are necessary as SET "file1Size=%%~zA"
results in SET "file1Size="
on first file not existing which means the environment variable file1Size
is not defined respectively deleted after the FOR command line.
The IF condition comparing the two file sizes would result in an exit of batch file processing because of a syntax error if either file1Size
or file2Size
does not exist on reaching this command line.
Please note that Windows command interpreter can handle only file sizes less than 2 GiB in the IF condition.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
for /?
goto /?
if /?
rem /?
set /?