仅使用批处理命令获取子文件夹的大小

Get size of the sub folders only using batch command

我在脚本中传递我的基本文件夹名称 (C:\Users\IAM\Desktop\MHW\*),并希望获取底层子文件夹的大小。下面的代码不起作用。需要帮助修复它。

@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

据我了解,值“%%G”没有传递给第二个 FOR 循环。

不幸的是,您不能通过另一个 for 变量或延迟扩展变量将根目录路径传递给 for /R 循环,您必须使用正常扩展变量 (%var%) 或参数引用 (%~1).

您可以通过将 for /R 循环放在通过 call 从主例程调用的子例程中来帮助自己。将保存结果的变量和根目录路径作为参数传递过来,并在子例程中分别像 %~1%~2 一样扩展它们。

@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

请注意,set /A 只能在 32 位空间中进行有符号整数运算,因此如果文件大小为 2 GiB 或更大,或者 sum 中的结果超过 231 - 1,你会收到错误的结果。