从 Windows 命令行获取文件夹大小 [英] Get Folder Size from Windows Command Line

查看:150
本文介绍了从 Windows 命令行获取文件夹大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows 中是否可以在不使用任何 3rd 方工具的情况下从命令行获取文件夹的大小?

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.

推荐答案

你可以递归地累加大小(以下是一个批处理文件):

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

然而,这有几个问题,因为 cmd 仅限于 32 位有符号整数算法.所以它的大小会超过 2 GiB 错误1.此外,它可能会多次计算符号链接和连接点,因此它充其量只是一个上限,而不是真实大小(不过,使用任何工具都会遇到这个问题).

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

另一种选择是 PowerShell:

An alternative is PowerShell:

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

或更短:

ls -r | measure -sum Length

如果你想要更漂亮:

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" }
}

您可以直接从 cmd 使用它:

You can use this directly from cmd:

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


1 我在批处理文件中确实有一个部分完成的 bignum 库,它至少可以正确地获得任意精度的整数加法.我真的应该发布它,我想:-)


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

这篇关于从 Windows 命令行获取文件夹大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆