Get size of the sub folders only using batch command

旧时模样 提交于 2019-12-02 10:22:05

问题


I am passing my base folder name (C:\Users\IAM\Desktop\MHW\*) in script and want to get the size of the underlying sub folders. The below code is not working. Need help to fix it.

@echo off
setLocal EnableDelayedExpansion
FOR /D %%G in ("C:\Users\IAM\Desktop\MHW\*") DO (
set /a value=0
set /a sum=0
FOR /R "%%G" %%I IN (*) DO (
set /a value=%%~zI/1024
set /a sum=!sum!+!value!
)
@echo %%G: !sum! K
)
pause

From my understanding, the value "%%G" is not getting passed to the second FOR loop.


回答1:


Unfortunately you cannot pass a root directory path to a for /R loop by another for variable nor a delayedly expanded variable, you must use a normally expanded variable (%var%) or an argument reference (%~1).

You can help yourself out by placing the for /R loop in a sub-routine that is called from the main routine via call. Pass the variable holding the result and the root directory path over as arguments and expand them like %~1 and %~2 in the sub-routine, respectively.

@echo off
setlocal EnableDelayedExpansion
for /D %%G in ("C:\Users\IAM\Desktop\MHW\*") do (
    rem Call the sub-routine here:
    call :SUB sum "%%~G"
    echo %%~G: !sum! KiB
)
pause
endlocal
exit /B

:SUB  rtn_sum  val_path
rem This is the sub-routine expecting two arguments:
rem the variable name holding the sum and the directory path;
set /A value=0, sum=0
rem Here the root directory path is accepted:
for /R "%~2" %%I in (*) do (
    rem Here is some rounding implemented by `+1024/2`:
    rem to round everything down, do not add anything (`+0`);
    rem to round everything up, add `+1024-1=1023` instead;
    set /A value=^(%%~zI+1024/2^)/1024
    set /A sum+=value
)
set "%~1=%sum%"
exit /B

Note that set /A is capable of signed integer arithetics in a 32-bit room only, so if a file is 2 GiB big or more, or the result in sum exceeds 231 - 1, you will receive wrong results.



来源:https://stackoverflow.com/questions/38396348/get-size-of-the-sub-folders-only-using-batch-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!