How to find file size only using windows shell?

I am trying to write a script that checks if the file size is greater than 0, and if so, it prints "more." I looked at this question and got some good ideas. I tried to implement what the second responder answered, but it does not work 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 to do this, it gives me the same size for all files, although I know that one of them is different. When I delete set size=0 , if the file size is 0, it gives the error 0 was unexpected at this time.

Any ideas on what I'm doing wrong? TIA!

+4
source share
5 answers

Try the following command:

 for %%I in (*.txt) do @echo %%~znI 

When I ran this, I got 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 are the file size in bytes ...

+2
source

If you want to use the actual environment variable inside this for block, you need a delayed extension:

 setlocal enabledelayedexpansion for %%i in (*.txt) do ( set size=0 set /A size=%%~zi echo %%i !size! if !size! GTR 0 echo greater ) 

Note that you need to replace %size% with !size! to cause slow expansion instead of the usual.

The problem is that ordinary environment variables expand when the operator is parsed; the for block is the only expression in this regard. Therefore, as soon as the loop starts the size value before using the loop.

A delayed extension (c ! ) Will expand the variables immediately before execution, and not during the analysis of the statement, so you will see the updated value from the loop.

+1
source

robocopy / L (dir you want size) (C: \ arbitrary folder) ./ Log: (C: \ arbitrary folder \ robolog.txt)

This will create a document whose size findstr Bytes C: \ robocopylog.txt -> getize.txt

Can you use for /? to go to the last getize.txt entry, which should contain the size of the entire directory. You will need to handle whether k is for Kilo m for megabytes or g for Gigs. What can be solved, since robocopy uses 0 as the owners of the place, so you will need to get only the 3rd and 4th tokens of the last line. 514.46 m

+1
source

I am 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 this is due to replacing the variable% size% and reset. I would still like to replace %%~zi with the variable name, but I think I will leave it if it works.

0
source

Here's how to do it in PowerShell. I hope it convinces you to switch to a more modern shell:

 PS C:\test> Get-ChildItem *.txt | ForEach-Object { Write-Host $_.name, $_.length } test.txt 16 test2.txt 5 
0
source

All Articles