Get Folder Size from Windows Command Line

WindowsPowershellCommand Line

Windows Problem Overview


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.

Windows Solutions


Solution 1 - Windows

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.

Solution 2 - Windows

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 :-)

Solution 3 - Windows

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

Solution 4 - Windows

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

Solution 5 - Windows

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

Solution 6 - Windows

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
}

Solution 7 - Windows

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**

Solution 8 - Windows

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.

Solution 9 - Windows

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

Solution 10 - Windows

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

Solution 11 - Windows

Open windows CMD and run follow command

dir /s c:\windows

Solution 12 - Windows

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.

Solution 13 - Windows

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

Solution 14 - Windows

::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.

Solution 15 - Windows

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)

Solution 16 - Windows

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

Solution 17 - Windows

The following one-liners can be used to determine the size of a folder.

The post is in Github Actions format, indicating which type of shell is used.

shell: pwsh
run: |
  Get-ChildItem -Path C:\temp -Recurse | Measure-Object -Sum Length


shell: cmd
run: |
  powershell -noprofile -command "'{0:N0}' -f (ls C:\temp -r | measure -s Length).Sum"

Solution 18 - Windows

It's better to use du because it's simple and consistent.

install scoop: iwr -useb get.scoop.sh | iex

install busybox: scoop install busybox

get dir size: du -d 0 . -h

Solution 19 - Windows

I was at this page earlier today, and after trying DU by SysInternals and piping the output etc etc. I said "Didn't I have to do this in VBscript? I got this to work for total size of ISOroot folder and all subfolders. Replace the fullpath with your own.

GetFolderSize.vbs

 Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder("C:\XPE\Custom\x64\IsoRoot")
    s = UCase(f.Name) & " uses " & f.size & " bytes."
    MsgBox s, 0, "Folder Size Info"

s=  FormatNumber(f.size/1024000,2) & " MB"
    MsgBox s, 0, "Folder Size Info"

s=  FormatNumber(f.size/1073741824,2) & " GB"
    MsgBox s, 0, "Folder Size Info"

Solution 20 - Windows

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.

Solution 21 - Windows

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEldad AssisView Question on Stackoverflow
Solution 1 - WindowsNir DuanView Answer on Stackoverflow
Solution 2 - WindowsJoeyView Answer on Stackoverflow
Solution 3 - WindowsfrizikView Answer on Stackoverflow
Solution 4 - WindowsSteveView Answer on Stackoverflow
Solution 5 - WindowsCustodioView Answer on Stackoverflow
Solution 6 - WindowsRyan LeeView Answer on Stackoverflow
Solution 7 - WindowsAlexander AnufrievView Answer on Stackoverflow
Solution 8 - WindowsFrinkTheBraveView Answer on Stackoverflow
Solution 9 - WindowsChienvelaView Answer on Stackoverflow
Solution 10 - WindowsSteveView Answer on Stackoverflow
Solution 11 - WindowsTuan Le AnhView Answer on Stackoverflow
Solution 12 - WindowsIllizianView Answer on Stackoverflow
Solution 13 - WindowsFrank NockeView Answer on Stackoverflow
Solution 14 - WindowsGustavo DavicoView Answer on Stackoverflow
Solution 15 - WindowsLior KirshnerView Answer on Stackoverflow
Solution 16 - WindowsjulesverneView Answer on Stackoverflow
Solution 17 - WindowsJens A. KochView Answer on Stackoverflow
Solution 18 - WindowsSodaCrisView Answer on Stackoverflow
Solution 19 - WindowsTony4219View Answer on Stackoverflow
Solution 20 - WindowsarpiView Answer on Stackoverflow
Solution 21 - WindowsrayView Answer on Stackoverflow