Reputation: 6163
I'm trying to write a script that checks if the size of a file is greater than 0 and if so, prints "greater". I looked at this question and got some good ideas. I tried to implement what the second answerer answered, but it's not working properly.
This is what I have so far:
for %%i in (*.txt) do (
set size=0
set /A size=%%~zi
echo %%i %size%
if %size% GTR 0 echo greater
)
When I try this, it keeps giving me the same size for all the files, even though I know that one of them is different. When I remove the set size=0
, if the file size is 0, it gives an error 0 was unexpected at this time.
Any ideas about what I'm doing wrong?
Upvotes: 4
Views: 9346
Reputation: 21
robocopy /L (dir you want the size of) (C:\arbitrary folder) . /Log:(C:\arbitrary folder\robolog.txt)
That wil create a document that has the size findstr Bytes C:\robocopylog.txt >>getsize.txt
You can use For /? to help navigate to the last entry of getsize.txt which should contain the size of the entire directory. You will have to handle whether it is k for Kilo m for mega bytes or g for Gigs Which can be solved since robocopy uses 0 as place holders so you would only need to get the 3rd and 4th token of the last line. 514.46 m
Upvotes: 1
Reputation: 354446
If you want to use an actual environment variable inside that for
block, you need delayed expansion:
setlocal enabledelayedexpansion
for %%i in (*.txt) do (
set size=0
set /A size=%%~zi
echo %%i !size!
if !size! GTR 0 echo greater
)
Note also that you need to replace %size%
by !size!
to trigger delayed expansion instead of the normal one.
The problem is that normal environment variables are expanded when a statement is parsed; the for
block is a single statement in that regard. So once the loop runs the value of size
from before the loop is used.
Delayed expansion (with !
) will expand the variables right before execution instead of when a statement is parsed so you will see the updated value from within the loop.
Upvotes: 2
Reputation: 21270
Here's how to do it in PowerShell. I hope it convinces you to upgrade to a more modern shell:
PS C:\test> Get-ChildItem *.txt | ForEach-Object { Write-Host $_.name, $_.length }
test.txt 16
test2.txt 5
Upvotes: 0
Reputation: 102398
Try this command:
for %%I in (*.txt) do @echo %%~znI
When I run this, I get the following result on Windows 7:
C:\Users\Leniel\Desktop>for %I in (*.txt) do @echo %~znI
14 test1
34 test2
where 14 and 34 is the file size in bytes...
Upvotes: 2
Reputation: 6163
I'm not sure why this caused the problem, but this code worked.
for %%i in (*.txt) do (
echo %%i %%~zi
echo %%~zi
if %%~zi GTR 0 echo greater
)
I think it had to do with when the %size% variable was getting replaced and reset. I'd still like to replace the %%~zi
with a variable name, but I think I'll leave it if it works.
Upvotes: 0