简体   繁体   English

从 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? Windows 是否可以在不使用任何第三方工具的情况下从命令行获取文件夹的大小?

I want the same result as you would get when right clicking the folder in the windows explorer → properties.我想要的结果与您在 windows 资源管理器 → 属性中右键单击该文件夹时得到的结果相同。

There is a built-in Windows tool for that:有一个内置的 Windows 工具

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 .如果您需要包含隐藏文件夹,请添加/a

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.但是,这有几个问题,因为cmd仅限于 32 位有符号整数算法。 So it will get sizes above 2 GiB wrong 1 .所以它的大小会超过 2 GiB 错误1 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:另一种选择是 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 :您可以直接从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. 1我在批处理文件中确实有一个部分完成的 bignum 库,它至少可以正确地获得任意精度的整数加法。 I should really release it, I guess :-)我真的应该发布它,我想:-)

I suggest to download utility DU from the Sysinternals Suite provided by Microsoft at this link http://technet.microsoft.com/en-us/sysinternals/bb896651我建议从 Microsoft 提供的 Sysinternals Suite 下载实用程序 DU,网址为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它们是每个 Windows Professional 的救星

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:相同但仅限 Powershell:

$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

如果您的计算机中安装了 git(越来越普遍),只需打开 MINGW32 并输入: du folder

I recommend using https://github.com/aleksaan/diskusage utility which I wrote.我建议使用我编写的https://github.com/aleksaan/diskusage实用程序。 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.此示例在 HDD 上以272 毫秒执行。

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** *** 服务器上的 3.5Tb 已扫描 3 分 12 秒**

Here comes a powershell code I write to list size and file count for all folders under current directory.这是我编写的 powershell 代码,用于列出当前目录下所有文件夹的大小和文件数。 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
}

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

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将 C:\\Program Files 更改为您想要的任何文件夹,如果在批处理文件中使用,请将 %A 更改为 %%A

It returns the size of the whole folder, including subfolders and hidden and system files, and works with folders over 2GB它返回整个文件夹的大小,包括子文件夹和隐藏文件和系统文件,并处理超过 2GB 的文件夹

It does write to the screen, so you'll have to use an interim file if you don't want that.它确实写入屏幕,因此如果您不想要,则必须使用临时文件。

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.我想这只有在目录相当静态并且其内容在两个 dir 命令的执行之间没有变化时才有效。 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: GetDirSummary.bat 脚本:

@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 GetDirSummary.bat c:\\temp

Output:输出:

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

I think your only option will be diruse (a highly supported 3rd party solution):我认为您唯一的选择将是 diruse(高度支持的 3rd 方解决方案):

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.不幸的是,Windows CLI 限制性很强,您也可以安装Cygwin ,与 cmd 相比,这是一个梦想。 That would give you access to the ported Unix tool du which is the basis of diruse on windows.这将使您可以访问移植的 Unix 工具 du,它是 Windows 上 diruse 的基础。

Sorry I wasn't able to answer your questions directly with a command you can run on the native cli.抱歉,我无法使用您可以在本机 cli 上运行的命令直接回答您的问题。

I got du.exe with my git distribution.我的 git 发行版得到了du.exe Another place might be aforementioned Microsoft or Unxutils .另一个地方可能是前面提到的 Microsoft 或Unxutils

Once you got du.exe in your path.一旦你的路径中有 du.exe。 Here's your fileSizes.bat :-)这是你的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

::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] ::获取 Dir 命令返回的行数(/-c 以消除数字分隔符:. ,)["Tokens = 3" 仅查看 Dir 中每行的第三列]

FOR /F "tokens=3" %%a IN ('dir /-c "%folderpath%"') DO set /ai=!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)仅适用于小于 2 GB 的文件夹(cmd 不处理超过 32 位的数字)
  • Does not read the number of bytes of the internal folders.不读取内部文件夹的字节数。

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 ).文件夹路径%folder%可以作为参数提供给此脚本 ( %1 )。
Ultimately, the results is held in the parameter %filesize%最终,结果保存在参数%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)注意: calcAccSize方法也可以打印文件夹的内容(上例中有注释)

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.与 Win Vista 或更新版本兼容。 XP only available if Robocopy is installed. XP 仅在安装了 Robocopy 时可用。 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.为了能够方便地使用这个批处理文件,将它放在您的 SendTo 文件夹中。 This will allow you to right click a folder or selection of folders, click on the SendTo option, and then select this batch file.这将允许您右键单击一个文件夹或选择的文件夹,单击 SendTo 选项,然后选择此批处理文件。

To find the SendTo folder on your computer simplest way is to open up cmd then copy in this line as is.要在您的计算机上找到 SendTo 文件夹,最简单的方法是打开 cmd,然后按原样复制此行。

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

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.帖子采用 Github Actions 格式,说明使用的 shell 类型。

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"

It's better to use du because it's simple and consistent.最好使用du ,因为它简单且一致。

install scoop: iwr -useb get.scoop.sh | iex安装独家新闻: iwr -useb get.scoop.sh | iex iwr -useb get.scoop.sh | iex

install busybox: scoop install busybox安装busybox: scoop install busybox

get dir size: du -d 0. -h获取目录大小: du -d 0. -h

I was at this page earlier today 4/27/22, and after trying DU by SysInternals ( https://learn.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.我今天早些时候在 22 年 4 月 27 日访问过此页面,在通过 SysInternals ( https://learn.microsoft.com/en-us/sysinternals/downloads/du ) 尝试 DU 并通过管道传输 output 等之后。我说“我不是必须在 VBscript 中执行此操作吗?我得到它来处理 ISOroot 文件夹和所有子文件夹的总大小。用你自己的文件夹完整路径替换它。它非常快。

GetFolderSize.vbs获取文件夹大小.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"

Use Windows Robocopy.使用 Windows Robocopy。

Put this in a batch file:将其放入批处理文件中:

@echo off
pushd "%~dp0"
set dir="C:\Temp"
for /f "tokens=3" %%i in ('robocopy /l /e /bytes %dir% %dir% ^| findstr Bytes') do @echo %%i
pause

Set the path for your folder in the dir variable.dir变量中设置文件夹的路径。

The for loop gets the 3rd string using tokens=3 , which is the size in bytes, from the robocopy findstr command. for循环使用tokens=3从 robocopy findstr 命令获取第三个字符串,这是以字节为单位的大小。

The /l switch in robocopy only lists the output of the command, so it doesn't actually run. robocopy 中的/l开关只列出了命令的 output,因此实际上并没有运行。

The /e switch in robocopy copies subdirectories including empty ones. robocopy 中的/e开关复制子目录,包括空目录。

The /bytes switch in robocopy copies subdirectories including empty ones. robocopy 中的/bytes开关复制子目录,包括空目录。
You can omit the /bytes switch to get the size in default folder properties sizes (KB, MB, GB...)您可以省略/bytes开关以获取默认文件夹属性大小(KB、MB、GB...)

The findstr | Bytes findstr | Bytes findstr | Bytes command finds the output of robocopy command which contains total folder size. findstr | Bytes命令查找 output 的 robocopy 命令,其中包含总文件夹大小。

And finally echo the index %%i to the console.最后将索引%%i回显到控制台。

If you need to save the folder size to a variable replace如果您需要将文件夹大小保存到变量替换

do @echo %%i

with

set size=%%i

If you want to send the folder size to another program through clipboard:如果你想通过剪贴板将文件夹大小发送到另一个程序:

echo %size% | clip

If you need to get the current folder size put the batch file into that folder and remove set dir="C:\Temp" and replace both %dir% with %cd% , which stands for current directory, like this:如果您需要获取当前文件夹大小,请将批处理文件放入该文件夹并删除set dir="C:\Temp"并将两个%dir%替换为%cd% ,它代表当前目录,如下所示:

@echo off
pushd "%~dp0"
for /f "tokens=3" %%i in ('robocopy /l /e /bytes "%cd%" "%cd%" ^| findstr Bytes') do @echo %%i
pause

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.我找到了在 cmd 中使用 vbscript 的简单解决方法。 It is tested in W2012R2 and W7.它在 W2012R2 和 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_.它设置环境变量 S_。 You can, of course, change last line to directly display result to eg当然,您可以更改最后一行以直接将结果显示为

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.您可以将其用作子程序或独立的 cmd。 Parameter is name of tested folder closed in quotes.参数是用引号括起来的测试文件夹的名称。

打开windows CMD并运行follow命令

dir /s c:\windows

仅获取总大小的最简单方法是 powershell,但仍然受到长度超过 260 个字符的路径名不包括在总数中的限制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM