Get size of the sub folders only using batch command

后端 未结 1 1281
生来不讨喜
生来不讨喜 2021-01-23 21:57

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.

相关标签:
1条回答
  • 2021-01-23 22:26

    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.

    0 讨论(0)
提交回复
热议问题