Quick Folder Size

From AutoIt Wiki
Jump to navigation Jump to search

Back to Samples

Illustrates:

  • Automation of DOS commands to accomplish a recursive folder scan.
  • Basic use of StringFormat

Notes:

  • This is a quicker version of Folder Size, but based on a similar principle. The difference is that this version lets DOS even do the adding up!
 ;--------------------------------------------------------------------------------
 ;Example of call to UDF _FolderSize()
 ;--------------------------------------------------------------------------------
     $sFolder = @TempDir
     $nFolderSize = _FolderSize($sFolder)
     If @error then
         ;failed
     Else
         Msgbox (4096 + 32,@ScriptName, StringFormat("Bytes in %s = %d", $sFolder, $nFolderSize))
     Endif
 
 
 Func _FolderSize($psFolder)
 ;--------------------------------------------------------------------------------
 ;Uses the DOS "dir" command to recurse through all subfolders,
 ;listing the size of each one, followed by a final summary total
 ;which is in fact the value we're after!
 ;--------------------------------------------------------------------------------
 Local $sFileList, $nFileList, $nTotalSize
 
     $sFileList = "C:\_FolderSize.LST"
     RunWait(@Comspec & " /C DIR """ & $psFolder & """ /s /A:-D /-C|find ""File(s)""> " & $sFileList,"", @SW_HIDE)
 #cs
 .. returns a list like this, 
 where the LAST LINE IS THE TOTAL OF ALL EARLIER LINES ;o)
               84 File(s)         792992 bytes
                6 File(s)          10400 bytes
                5 File(s)           1648 bytes
               85 File(s)        1721301 bytes
               77 File(s)          36400 bytes
               81 File(s)          45170 bytes
              338 File(s)        2607911 bytes
 #ce
 
     $nFileList = FileOpen($sFileList, 0)  ;0=open
     If $nFileList = -1 then
         ;Couldn't open list of files in designated folder
         SetError(1)
         Return 0
     Endif
 
 ;Read the listfile, and keep the value from the last line
     $nTotalSize = 0
     While 1
         $sFolderSize = FileReadLine($nFileList)
         if @error = -1 then;EOF
             ExitLoop
         endif
         $sTotalSize = $sFolderSize                        
     Wend
     $nTotalSize = StringMid($sTotalSize, 25, 15)
 
 ;Cleanup
     FileClose($nFileList)
     FileDelete($sFileList)
     
     Return $nTotalSize
     
 EndFunc