列出文件大小给定结构中的所有文件夹和子文件夹

乔尔

我正在尝试列出光盘的文件夹结构和每个文件夹的大小。

我的文件夹结构有所降低,现在我只需要输出每个文件夹的大小即可。

根据https://docs.microsoft.com/zh-CN/windows-server/administration/windows-commands/dir,没有显示文件大小的标志-仅将其隐藏。我猜我在这里走了错误的路线,但我们会提供任何帮助。

这是到目前为止我得到的:

dir /s /b /o:n /a:d > "C:\folderlist.txt"

预期产量:

C:\WINDOWS\system32\downlevel 400mb
C:\WINDOWS\system32\drivers 100mb
C:\WINDOWS\system32\DriverState 4kb
C:\WINDOWS\system32\DriverStore 1kb
C:\WINDOWS\system32\DRVSTORE 1gb

文件大小的缩写,即(mb,kb,gb,tb)无关紧要。只要它以某种可量化的方式显示出文件夹的大小。

也欢迎使用Powershell替代方案。

mklement0

一个基于montonero的有用答案并改进以下方面的PowerShell解决方案

  • 控制递归深度
  • 改善性能
  • 与其他cmdlet更好地集成以实现可组合的功能

基于Get-DirectorySize以下定义的函数的示例调用

# Get the size of the current directory (only).
Get-DirectorySize

# As requested by the OP:
# Recursively report the sizes of all subdirectories in the current directory.
Get-DirectorySize -Recurse -ExcludeSelf

# Get the size of all child directories and sort them by size, from largest
# to smallest, showing only the 5 largest ones:
Get-DirectorySize -Depth 1 -ExcludeSelf |
  Sort-Object Size -Descending |
    Select-Object -First 5

最后一条命令的输出示例:

FullName                           FriendlySize       Size
--------                           ------------       ----
C:\Users\jdoe\AppData                3.27gb     3514782772
C:\Users\jdoe\Desktop              801.40mb      840326199
C:\Users\jdoe\.nuget               778.97mb      816814396
C:\Users\jdoe\.vscode              449.12mb      470931418
C:\Users\jdoe\Projects             104.07mb      109127742

请注意,属性.FriendlySize包含一个友好的,自动缩放的大小字符串表示形式,而.Size数字([long])则包含实际的字节数,这有助于进一步的编程过程。

注意:仅在实现方便的情况下,将属性添加到便于友好显示的输出对象中正确的Powershell方法将是根据输出对象类型定义格式说明,请参阅docs

注意事项(也适用于链接的答案):

  • 报告逻辑大小,即文件数据所需的实际字节数,与文件上大小不同,磁盘上大小通常较大这是由于文件占据了固定大小的块;相反,压缩和稀疏文件占用更少的磁盘空间。

  • 递归(和-Recurse和/或-Depth)的实现效率低下,因为所遇到的每个目录的子树都将被完全扫描。文件系统缓存对此有所帮助。


Get-DirectorySize 源代码

注意:需要Windows PowerShell v3 +;还与PowerShell Core兼容

function Get-DirectorySize
{

  param(
    [Parameter(ValueFromPipeline)] [Alias('PSPath')]
    [string] $LiteralPath = '.',
    [switch] $Recurse,
    [switch] $ExcludeSelf,
    [int] $Depth = -1,
    [int] $__ThisDepth = 0 # internal use only
  )

  process {

    # Resolve to a full filesystem path, if necessary
    $fullName = if ($__ThisDepth) { $LiteralPath } else { Convert-Path -ErrorAction Stop -LiteralPath $LiteralPath }

    if ($ExcludeSelf) { # Exclude the input dir. itself; implies -Recurse

      $Recurse = $True
      $ExcludeSelf = $False

    } else { # Process this dir.

      # Calculate this dir's total logical size.
      # Note: [System.IO.DirectoryInfo].EnumerateFiles() would be faster, 
      # but cannot handle inaccessible directories.
      $size = [Linq.Enumerable]::Sum(
        [long[]] (Get-ChildItem -Force -Recurse -File -LiteralPath $fullName).ForEach('Length')
      )

      # Create a friendly representation of the size.
      $decimalPlaces = 2
      $padWidth = 8
      $scaledSize = switch ([double] $size) {
        {$_ -ge 1tb } { $_ / 1tb; $suffix='tb'; break }
        {$_ -ge 1gb } { $_ / 1gb; $suffix='gb'; break }
        {$_ -ge 1mb } { $_ / 1mb; $suffix='mb'; break }
        {$_ -ge 1kb } { $_ / 1kb; $suffix='kb'; break }
        default       { $_; $suffix='b'; $decimalPlaces = 0; break }
      }

      # Construct and output an object representing the dir. at hand.
      [pscustomobject] @{
        FullName = $fullName
        FriendlySize = ("{0:N${decimalPlaces}}${suffix}" -f $scaledSize).PadLeft($padWidth, ' ')
        Size = $size
      }

    }

    # Recurse, if requested.
    if ($Recurse -or $Depth -ge 1) {
      if ($Depth -lt 0 -or (++$__ThisDepth) -le $Depth) {
        # Note: This top-down recursion is inefficient, because any given directory's
        #       subtree is processed in full.
        Get-ChildItem -Force -Directory -LiteralPath $fullName |
          ForEach-Object { Get-DirectorySize -LiteralPath $_.FullName -Recurse -Depth $Depth -__ThisDepth $__ThisDepth }
      }
    }

  }

}

这是该功能的基于注释的帮助例如,如果将功能添加到您的功能中,$PROFILE则将帮助直接放置在功能上方或功能内部,以便获得对的支持-?并与之自动集成Get-Help

<#
.SYNOPSIS
Gets the logical size of directories in bytes.

.DESCRIPTION
Given a literal directory path, output that directory's logical size, i.e.,
the sum of all files contained in the directory, including hidden ones.

NOTE: 
* The logical size is distinct from the size on disk, given that files
  are stored in fixed-size blocks. Furthermore, files can be compressed
  or sparse.
  Thus, the size of regular files on disk is typically greater than
  their logical size; conversely, compressed and sparse files require less
  disk space.
  Finally, the list of child items maintained by the filesystem for each 
  directory requires disk space too.

* Wildcard expressions aren't directly supported, but you may pipe in
  Output from Get-ChildItem / Get-Item; if files rather than directotries 
  happen to be among the input objects, their size is reported as-is.

CAVEATS:
 * Can take a long time to run with large directory trees, especially with
   -Recurse.
* Recursion is implemented inefficently.

.PARAMETER LiteralPath
The literal path of a directory. May be provided via the pipeline.

.PARAMETER Recurse
Calculates the logical size not only of the input directory itself, but of
all subdirectories in its subtree too.
To limit the recursion depth, use -Depth.

.PARAMETER Depth
Limits the recursion depth to the specified number of levels. Implies -Recurse.
Note that 0 means no recursion. Use just -Recurse in order not to limit the
recursion.

.PARAMETER ExcludeSelf
Excludes the target directory itself from the size calculation.
Implies -Recurse. Since -Depth implies -Recurse, you could use -ExcludeSelf
-Depth 1 to report only the sizes of the immediate subdirectories.

.OUTPUTS
[pscustomobject] instances with properties FullName, Size, and FriendlySize.

.EXAMPLE
Get-DirectorySize

Gets the logical size of the current directory.

.EXAMPLE
Get-DirectorySize -Recurse

Gets the logical size of the current directory and all its subdirectories.

.EXAMPLE
Get-DirectorySize /path/to -ExcludeSelf -Depth 1 | Sort-Object Size

Gets the logical size of all child directories in /path/to without including
/path/to itself, and sorts the result by size (largest last).
#>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章