Advertisement
horshack

Calculate Average File Size in KB (Windows Batch File)

Feb 17th, 2020
892
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Batch 1.72 KB | None | 0 0
  1. @echo off
  2.  
  3. ::
  4. :: Calculates the average size of files (KB) for a given directory
  5. :: DOS/Windows batch files only support integers for numbers and only 32-bit integers,
  6. :: so to prevent rollover of the running sum of the file sizes we maintain the size in KB,
  7. :: and keep a seperate rolling sum of the KB modula of file sizes, which we'll use to round
  8. :: the sum up by 1KB if the average of the modulas is >= 1/2 a KB
  9. ::
  10.  
  11. :: set initial running count/sum vars
  12. set /a fileCount = 0
  13. set /a fileSizeSumKb_Main = 0
  14. set /a fileSizeSumKb_Modula = 0
  15.  
  16. :: Iterate through each file in the path specified on the command line
  17. FOR %%A in (%1\*.*) do CALL :AddFileToRunningTotals %%A
  18.  
  19. :: if the sum of the 1KB-modula of every file's size is > = 512 then we round up by 1KB
  20. set /a fileSizeSumKb_With_Modula = %fileSizeSumKb_Main% + (%fileSizeSumKb_Modula%/1024) + (%fileSizeSumKb_Modula% %% 1024 / 512)
  21.  
  22. :: Calculate the average. If the modula of the division to derive the average >= 0.50 then round up the result by 1KB
  23. :: Note: we have to calculate > = 0.50 by multiplying the modula result by 100 then dividing 50 since we can only use integer math
  24. set /a fileSizeAverageKb = (%fileSizeSumKb_With_Modula% / %fileCount%) + (%fileSizeSumKb_With_Modula% %% %fileCount% * 100 / %fileCount% / 50)
  25.  
  26. :: Display results and exit
  27. echo fileCount: %fileCount%, total size: %fileSizeSumKb_With_Modula% KB, Average File Size: %fileSizeAverageKb% KB
  28. GOTO:EOF
  29.  
  30. :: Adds the current file to the running total of files and file sizes
  31. :AddFileToRunningTotals
  32. set FILELEN=%~z1
  33. IF [%FILELEN%] == [] GOTO:EOF
  34. set /a fileSizeSumKb_Main += (%FILELEN% / 1024)
  35. set /a fileSizeSumKb_Modula +=  ((%FILELEN% %% 1024 + 1024) %% 1024)
  36. set /a fileCount += 1
  37. GOTO:EOF
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement