[windows] Get Folder Size from Windows Command Line

Is it possible in Windows to get a folder's size from the command line without using any 3rd party tool?

I want the same result as you would get when right clicking the folder in the windows explorer ? properties.

This question is related to windows powershell command-line

The answer is


You can just add up sizes recursively (the following is a batch file):

@echo off
set size=0
for /r %%x in (folder\*) do set /a size+=%%~zx
echo %size% Bytes

However, this has several problems because cmd is limited to 32-bit signed integer arithmetic. So it will get sizes above 2 GiB wrong1. Furthermore it will likely count symlinks and junctions multiple times so it's at best an upper bound, not the true size (you'll have that problem with any tool, though).

An alternative is PowerShell:

Get-ChildItem -Recurse | Measure-Object -Sum Length

or shorter:

ls -r | measure -sum Length

If you want it prettier:

switch((ls -r|measure -sum Length).Sum) {
  {$_ -gt 1GB} {
    '{0:0.0} GiB' -f ($_/1GB)
    break
  }
  {$_ -gt 1MB} {
    '{0:0.0} MiB' -f ($_/1MB)
    break
  }
  {$_ -gt 1KB} {
    '{0:0.0} KiB' -f ($_/1KB)
    break
  }
  default { "$_ bytes" }
}

You can use this directly from cmd:

powershell -noprofile -command "ls -r|measure -sum Length"

1 I do have a partially-finished bignum library in batch files somewhere which at least gets arbitrary-precision integer addition right. I should really release it, I guess :-)


The following script can be used to fetch and accumulate the size of each file under a given folder.
The folder path %folder% can be given as an argument to this script (%1).
Ultimately, the results is held in the parameter %filesize%

@echo off
SET count=1
SET foldersize=0
FOR /f "tokens=*" %%F IN ('dir /s/b %folder%') DO (call :calcAccSize "%%F")
echo %filesize%
GOTO :eof

:calcAccSize
 REM echo %count%:%1
 REM set /a count+=1
 set /a foldersize+=%~z1
 GOTO :eof

Note: The method calcAccSize can also print the content of the folder (commented in the example above)


So here is a solution for both your requests in the manner you originally asked for. It will give human readability filesize without the filesize limits everyone is experiencing. Compatible with Win Vista or newer. XP only available if Robocopy is installed. Just drop a folder on this batch file or use the better method mentioned below.

@echo off
setlocal enabledelayedexpansion
set "vSearch=Files :"

For %%i in (%*) do (
    set "vSearch=Files :"
    For /l %%M in (1,1,2) do ( 
        for /f "usebackq tokens=3,4 delims= " %%A in (`Robocopy "%%i" "%%i" /E /L /NP /NDL /NFL ^| find "!vSearch!"`) do (
            if /i "%%M"=="1" (
                set "filecount=%%A"
                set "vSearch=Bytes :"
            ) else (
                set "foldersize=%%A%%B"
            )
        )
    )
    echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!
    REM remove the word "REM" from line below to output to txt file
    REM echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!>>Folder_FileCountandSize.txt
)
pause

To be able to use this batch file conveniently put it in your SendTo folder. This will allow you to right click a folder or selection of folders, click on the SendTo option, and then select this batch file.

To find the SendTo folder on your computer simplest way is to open up cmd then copy in this line as is.

explorer C:\Users\%username%\AppData\Roaming\Microsoft\Windows\SendTo


If you have git installed in your computer (getting more and more common) just open MINGW32 and type: du folder


Easiest method to get just the total size is powershell, but still is limited by fact that pathnames longer than 260 characters are not included in the total


Oneliner:

powershell -command "$fso = new-object -com Scripting.FileSystemObject; gci -Directory | select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName | sort Size -Descending | ft @{l='Size [MB]'; e={'{0:N2}    ' -f ($_.Size / 1MB)}},FullName"

Same but Powershell only:

$fso = new-object -com Scripting.FileSystemObject
gci -Directory `
  | select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName `
  | sort Size -Descending `
  | ft @{l='Size [MB]'; e={'{0:N2}    ' -f ($_.Size / 1MB)}},FullName

This should produce the following result:

Size [MB]  FullName
---------  --------
580,08     C:\my\Tools\mongo
434,65     C:\my\Tools\Cmder
421,64     C:\my\Tools\mingw64
247,10     C:\my\Tools\dotnet-rc4
218,12     C:\my\Tools\ResharperCLT
200,44     C:\my\Tools\git
156,07     C:\my\Tools\dotnet
140,67     C:\my\Tools\vscode
97,33      C:\my\Tools\apache-jmeter-3.1
54,39      C:\my\Tools\mongoadmin
47,89      C:\my\Tools\Python27
35,22      C:\my\Tools\robomongo

I guess this would only work if the directory is fairly static and its contents don't change between the execution of the two dir commands. Maybe a way to combine this into one command to avoid that, but this worked for my purpose (I didn't want the full listing; just the summary).

GetDirSummary.bat Script:

@echo off
rem  get total number of lines from dir output
FOR /F "delims=" %%i IN ('dir /S %1 ^| find "asdfasdfasdf" /C /V') DO set lineCount=%%i
rem  dir summary is always last 3 lines; calculate starting line of summary info
set /a summaryStart="lineCount-3"
rem  now output just the last 3 lines
dir /S %1 | more +%summaryStart%

Usage:

GetDirSummary.bat c:\temp

Output:

 Total Files Listed:
          22 File(s)         63,600 bytes
           8 Dir(s)  104,350,330,880 bytes free

I got du.exe with my git distribution. Another place might be aforementioned Microsoft or Unxutils.

Once you got du.exe in your path. Here's your fileSizes.bat :-)

@echo ___________
@echo DIRECTORIES
@for /D %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo FILES
@for %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo TOTAL
@du.exe -sh "%CD%"

?

___________
DIRECTORIES
37M     Alps-images
12M     testfolder
_____
FILES
765K    Dobbiaco.jpg
1.0K    testfile.txt
_____
TOTAL
58M    D:\pictures\sample

Here comes a powershell code I write to list size and file count for all folders under current directory. Feel free to re-use or modify per your need.

$FolderList = Get-ChildItem -Directory
foreach ($folder in $FolderList)
{
    set-location $folder.FullName
    $size = Get-ChildItem -Recurse | Measure-Object -Sum Length
    $info = $folder.FullName + "    FileCount: " + $size.Count.ToString() + "   Size: " + [math]::Round(($size.Sum / 1GB),4).ToString() + " GB"
    write-host $info
}

I solved similar problem. Some of methods in this page are slow and some are problematic in multilanguage environment (all suppose english). I found simple workaround using vbscript in cmd. It is tested in W2012R2 and W7.

>%TEMP%\_SFSTMP$.VBS ECHO/Set objFSO = CreateObject("Scripting.FileSystemObject"):Set objFolder = objFSO.GetFolder(%1):WScript.Echo objFolder.Size
FOR /F %%? IN ('CSCRIPT //NOLOGO %TEMP%\_SFSTMP$.VBS') DO (SET "S_=%%?"&&(DEL %TEMP%\_SFSTMP$.VBS))

It set environment variable S_. You can, of course, change last line to directly display result to e.g.

FOR /F %%? IN ('CSCRIPT //NOLOGO %TEMP%\_SFSTMP$.VBS') DO (ECHO "Size of %1 is %%?"&&(DEL %TEMP%\_SFSTMP$.VBS))

You can use it as subroutine or as standlone cmd. Parameter is name of tested folder closed in quotes.


This code is tested. You can check it again.

@ECHO OFF
CLS
SETLOCAL
::Get a number of lines contain "File(s)" to a mytmp file in TEMP location.
DIR /S /-C | FIND "bytes" | FIND /V "free" | FIND /C "File(s)" >%TEMP%\mytmp
SET /P nline=<%TEMP%\mytmp
SET nline=[%nline%]
::-------------------------------------
DIR /S /-C | FIND "bytes" | FIND /V "free" | FIND /N "File(s)" | FIND "%nline%" >%TEMP%\mytmp1
SET /P mainline=<%TEMP%\mytmp1
CALL SET size=%mainline:~29,15%
ECHO %size%
ENDLOCAL
PAUSE

::Get a number of lines that Dir commands returns (/-c to eliminate number separators: . ,) ["Tokens = 3" to look only at the third column of each line in Dir]

FOR /F "tokens=3" %%a IN ('dir /-c "%folderpath%"') DO set /a i=!i!+1

Number of the penultimate line, where is the number of bytes of the sum of files:

set /a line=%i%-1

Finally get the number of bytes in the penultimate line - 3rd column:

set i=0
FOR /F "tokens=3" %%a IN ('dir /-c "%folderpath%"') DO (
  set /a i=!i!+1
  set bytes=%%a
  If !i!==%line% goto :size  
)
:size
echo %bytes%

As it does not use word search it would not have language problems.

Limitations:

  • Works only with folders of less than 2 GB (cmd does not handle numbers of more than 32 bits)
  • Does not read the number of bytes of the internal folders.

I suggest to download utility DU from the Sysinternals Suite provided by Microsoft at this link http://technet.microsoft.com/en-us/sysinternals/bb896651

usage: du [-c] [-l <levels> | -n | -v] [-u] [-q] <directory>
   -c     Print output as CSV.
   -l     Specify subdirectory depth of information (default is all levels).
   -n     Do not recurse.
   -q     Quiet (no banner).
   -u     Count each instance of a hardlinked file.
   -v     Show size (in KB) of intermediate directories.


C:\SysInternals>du -n d:\temp

Du v1.4 - report directory disk usage
Copyright (C) 2005-2011 Mark Russinovich
Sysinternals - www.sysinternals.com

Files:        26
Directories:  14
Size:         28.873.005 bytes
Size on disk: 29.024.256 bytes

While you are at it, take a look at the other utilities. They are a life-saver for every Windows Professional


Try:

SET FOLDERSIZE=0
FOR /F "tokens=3" %A IN ('DIR "C:\Program Files" /a /-c /s ^| FINDSTR /C:" bytes" ^| FINDSTR /V /C:" bytes free"') DO SET FOLDERSIZE=%A

Change C:\Program Files to whatever folder you want and change %A to %%A if using in a batch file

It returns the size of the whole folder, including subfolders and hidden and system files, and works with folders over 2GB

It does write to the screen, so you'll have to use an interim file if you don't want that.


I think your only option will be diruse (a highly supported 3rd party solution):

Get file/directory size from command line

The Windows CLI is unfortuntely quite restrictive, you could alternatively install Cygwin which is a dream to use compared to cmd. That would give you access to the ported Unix tool du which is the basis of diruse on windows.

Sorry I wasn't able to answer your questions directly with a command you can run on the native cli.


There is a built-in Windows tool for that:

dir /s 'FolderName'

This will print a lot of unnecessary information but the end will be the folder size like this:

 Total Files Listed:
       12468 File(s)    182,236,556 bytes

If you need to include hidden folders add /a.


I recommend using https://github.com/aleksaan/diskusage utility which I wrote. Very simple and helpful. And very fast.

Just type in a command shell

diskusage.exe -path 'd:/go; d:/Books'

and get list of folders arranged by size

  1.| DIR: d:/go      | SIZE: 325.72 Mb   | DEPTH: 1 
  2.| DIR: d:/Books   | SIZE:  14.01 Mb   | DEPTH: 1 

This example was executed at 272ms on HDD.

You can increase depth of subfolders to analyze, for example:

diskusage.exe -path 'd:/go; d:/Books' -depth 2

and get sizes not only for selected folders but also for its subfolders

  1.| DIR: d:/go            | SIZE: 325.72 Mb   | DEPTH: 1 
  2.| DIR: d:/go/pkg        | SIZE: 212.88 Mb   | DEPTH: 2 
  3.| DIR: d:/go/src        | SIZE:  62.57 Mb   | DEPTH: 2 
  4.| DIR: d:/go/bin        | SIZE:  30.44 Mb   | DEPTH: 2 
  5.| DIR: d:/Books/Chess   | SIZE:  14.01 Mb   | DEPTH: 2 
  6.| DIR: d:/Books         | SIZE:  14.01 Mb   | DEPTH: 1 
  7.| DIR: d:/go/api        | SIZE:   6.41 Mb   | DEPTH: 2 
  8.| DIR: d:/go/test       | SIZE:   5.11 Mb   | DEPTH: 2 
  9.| DIR: d:/go/doc        | SIZE:   4.00 Mb   | DEPTH: 2 
 10.| DIR: d:/go/misc       | SIZE:   3.82 Mb   | DEPTH: 2 
 11.| DIR: d:/go/lib        | SIZE: 358.25 Kb   | DEPTH: 2 

*** 3.5Tb on the server has been scanned for 3m12s**


Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to powershell

Why powershell does not run Angular commands? How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line? How to print environment variables to the console in PowerShell? Check if a string is not NULL or EMPTY The term 'ng' is not recognized as the name of a cmdlet VSCode Change Default Terminal 'Connect-MsolService' is not recognized as the name of a cmdlet Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet Change directory in PowerShell

Examples related to command-line

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Flutter command not found Angular - ng: command not found how to run python files in windows command prompt? How to run .NET Core console app from the command line Copy Paste in Bash on Ubuntu on Windows How to find which version of TensorFlow is installed in my system? How to install JQ on Mac by command-line? Python not working in the command line of git bash Run function in script from command line (Node JS)