Get size of a file and save it to a variable in Windows console?
2014-07
I'm making a windows batch script, I need to get the specific size of a file so I can Insert that and other values I already got to a database, but I just can't figure out the proper way to do it.
Assuming the name of the file is c:\test!basename!.zip
(I'm in a for loop here), how can I get the filesize and store it to a variable?
The machine is a Win2008 Server.
ANSWER
EliadTech proposed a solution that I've already tried
for %I in (test.jpg) do @echo %~zI
That worked directly in the command prompt, but failed inside the script.
EliadTech, as we already suspected, thought of checking the escaping, so we got this
for %%I in (c:\test\!basename!.zip) do @echo yay %%~zI
Works like a charm.
Kinda dumb mistake, but bash has spoiled me beyond repair :)
There are a few suggestions here. I think this is best suited to you:
for %I in (test.jpg) do @echo %~zI
Is it considered necessary or good practice to unload variables used in Windows batch files?
For example in the following code, is the set myFolder=
at the end necessary?
@echo off
set myFolder="C:\Temp\Batchfiles"
echo %myFolder%
set myFolder=
I have seen this in a number of places online, surely the variables are unloaded automatically when the batch file ends?
SET
will set a global environment variable. It will persist after the execution of your script.
Let's have a look at an example.
First, I clear the variable to make sure it doesn't exist.
C:\Users\Oliver\Desktop>set TEST=
A quick test:
C:\Users\Oliver\Desktop>echo %TEST%
%TEST%
Let's create that batch file and execute it:
C:\Users\Oliver\Desktop>echo set TEST=something>test.bat
C:\Users\Oliver\Desktop>test.bat
C:\Users\Oliver\Desktop>set TEST=something
Let's see the value of TEST after the execution of my .bat
file:
C:\Users\Oliver\Desktop>echo %TEST%
something
So, yes, clearing the variable at the end of the script is good practice.
Even better would be to use SETLOCAL
and ENDLOCAL
to avoid the whole problem.
Here, I created a new .bat
file that uses SETLOCAL
and ENDLOCAL
:
C:\Users\Oliver\Desktop>type test.bat
setlocal
set TEST=something
endlocal
Let's clear TEST
and echo it to make sure we start clean:
C:\Users\Oliver\Desktop>set TEST=
C:\Users\Oliver\Desktop>echo %TEST%
%TEST%
Great, now let's run the new .bat
:
C:\Users\Oliver\Desktop>test.bat
C:\Users\Oliver\Desktop>setlocal
C:\Users\Oliver\Desktop>set TEST=something
C:\Users\Oliver\Desktop>endlocal
Now TEST
will still be empty:
C:\Users\Oliver\Desktop>echo %TEST%
%TEST%