不幸的是不能由另一for
变量传递一个根目录路径到for /R
环,也不是一个delayedly扩展变量,则必须使用一个正常扩张变量(%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
能够有符号整数arithetics在32位的房间而已,所以如果一个文件是2吉布大或以上,或导致sum
超过2 - 1,你会收到错误的结果。
谢谢!唯一的事情就是尺寸小于实际的尺寸。将解决它。 – p2k
'set/A'仅对32位整数算术进行签名,所以如果某些文件大于2 GiB或总和太大,您将得到意外的结果... – aschipfl