Get Folder Size from Windows Command Line

前端 未结 17 2427
滥情空心
滥情空心 2020-11-28 18:52

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

17条回答
  •  没有蜡笔的小新
    2020-11-28 19:35

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

提交回复
热议问题