ChatGPT解决这个技术问题 Extra ChatGPT

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.


k
kaartic

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


Steve, in my eyes PowerShell is way more Unix-y than Unix in that most core commands are really orthogonal. In Unix du gives directory size but all it's doing is walking the tree and summing up. Something that can be very elegantly expressed in a pipeline like here :-). So for PowerShell I usually look for how you can decompose the high-level goal into suitable lower-level operations.
I see, it seems to ignore hidden folders that way. ls -force -r works if I want to include hidden folders as well.
folder\* is not working for me the size of the folder that i put in the place shows 0 bytes, Is there any solution?
A slightly better looking version: powershell -noprofile -command "'{0:N0}' -f (ls -r|measure -s Length).Sum"
@athos: Use %1 in place of folder in the batch file, or add a parameter to the PowerShell script and add that as an argument to Get-ChildItem. But perhaps such things are better asked as a separate question if you have trouble with that part (as it has no relation to the original question here).
M
Mark Amery

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.


This is the most elegant solution if you don't require an integer return value. Note: the '/a' switch will include hidden and system files in the total size.
I guess it's not possible to print file sizes in some more useful units, like kB or MB, right?
Double quotes instead of single quotes.
only works if i rearrange the command here - dir 'FolderName'/s
f
frizik

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

Is there a way to show all the files and size in Mb in the base folder as well? In this case `C:\my\Tools`
Plus it breaks when there are lots of folders (For example in the C: drive)
0.00 C:\Windows can I optimize this for all folder, tried already run as admin
this is good but it truncates my component folder names. what is the command to display them entirely?
@sean.net do you mean it ends with "..." in case of long folders? That's how ft (Format-Table) works. You can try fl instead (Format-List)
S
Steve

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


That's hardly "without any 3rd-party tool", I guess.
Oh right, but it thought that family should not be considered '3rd party'.
Well, granted, but it's still an additional download (or using \\live.sysinternals.com if that still exists). I wholeheartedly agree though, that all the sysinternals tools should be included by default. Although for many uses PowerShell is a quite worthy replacement.
Did someone say Powershell? Try the following: "{0:N2}" -f ((Get-ChildItem C:\Temp -Recurse | Measure-Object -Property Length -Sum).Sum / 1MB) + " MB"
I suggest you all to download whatever Mark Russinovich develops :) I keep seeing this name whenever I find a tool saving my life.
C
Custodio

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


You can use the following command du -h -d 1 folder | sort -h if you want human readable size, one level of subdirectories only, and sort by size.
R
Ryan Lee

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
}

Works for me. Useful if your on a headless server.
Simple and elegant! My version: $FolderList = Get-ChildItem -Directory -Force; $data = foreach ($folder in $FolderList) { set-location $folder.FullName; $size = Get-ChildItem -Recurse -Force | Measure-Object -Sum Length; $size | select @{n="Path"; e={$folder.Fullname}}, @{n="FileCount"; e={$_.count}}, @{n="Size"; e={$_.Sum}} } This will provide objects (more Powershell-ish), 'FileCount' and 'Size' are integers (so you can process them later, if needed), and 'Size' is in bytes, but you could easily convert it to GB (or the unit you want) with $Data.Size / 1GB.
Or a one-liner: $Data = dir -Directory -Force | %{ $CurrentPath = $_.FullName; Get-ChildItem $CurrentPath -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Sum Length | select @{n="Path"; e={$CurrentPath}}, @{n="FileCount"; e={$_.count}}, @{n="Size"; e={$_.Sum}} }
I like this one best, but isn't the set-location unnecessary? You can just go Get-ChildItem $folder.FullName, that way you come out the other side without the current directory changing underneath you.
Thanks @BenderBoy. It's better to remove set-location and use Get-ChildItem $folder.FullName directly.
R
Ro Yo Mi

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


New version released! github.com/aleksaan/diskusage Improvments: 1) correct work with symlink's sizes 2) orevall info about analyzed objects
Version 2.0.2 released! github.com/aleksaan/diskusage/releases/tag/v2.0.2 - Configuration file instead inline parameters - Simple usage mode (copy diskusage executable to any folder, run it and get results) - Correct results output (correct end of line symbol win/unix) - Save results to file or get it in console mode (option 'tofile')
Please, make note that you are an author. (From stackoverflow.com/help/promotion: "However, you must disclose your affiliation in your answers.")
Yes, I am author of github.com/aleksaan/diskusage program
Version 2.1.0 has been released. github.com/aleksaan/diskusage/releases/tag/v2.1.0 - memory consumpion optimization - reducing time of analysis - bug fixing
F
FrinkTheBrave

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.


C
Chienvela

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

Thanks, it works for me with folders which smaller than 1GB, but for example, I have a folder of 3,976,317,115 bytes (3.70GB), and the script return to me this string ") 932", do you know why?
S
Steve

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

T
Tuan Le Anh

Open windows CMD and run follow command

dir /s c:\windows

this gives the size of every file - it's still spinning after 5 minutes when the powershell script gave me the totals in about 2 seconds
F
Frank Nocke

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

I
Illizian

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.


If you just need du then Cygwin is way overkill. Just go with GnuWin32.
Indeed it is overkill, but it's also awesome. +1 for your post above @joey (haven't got the rep to do it literally :( )
In my humble opinion Cygwin may be useful to some but it's far from awesome and rather horrible. But I guess Unix users say the same about Wine.
"wine" - shudder, I use Cygwin on my development laptop because the battery life is appalling under linux and it's not convenient to run a VM on it. It takes some setting up, but Cygwin is brilliant for those among us who miss the nix shell in Windows, personally I don't like Powershell I may have to check GnuWin out though. Thanks @Joey.
G
Gustavo Davico

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


L
Lior Kirshner

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)


j
julesverne

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


For anyone worried Robocopy will move files.. don't. the /l option only lists. In addition, Robocopy is not 3rd party, Robocopy is installed in Windows by default from Vista up, XP you need to install it.
Thanks for the addition. Glad to see this thread still attracting attention ;-) Might want to add how to install robocopy (great tool!).
I posted the original solution 4 years earlier here on SO. Using robocopy by far is the fastest solution.
J
Jens A. Koch

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"

S
SodaCris

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


Right, but this is not windows native in 2012 ;-) +1 anyway for the idea
T
Tony4219

I was at this page earlier today 4/27/22, and after trying DU by SysInternals (https://docs.microsoft.com/en-us/sysinternals/downloads/du) 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 Folder fullpath with your own. It's very fast.

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"

a
arpi

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.


r
ray

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


This is a bad and poor answer. What is the command line or code?