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

2023-12-24

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

我已经确定了文件夹结构,现在我只需要输出每个文件夹的大小。

根据https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/dir https://learn.microsoft.com/en-us/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 替代品也受欢迎。


A PowerShell解决方案建立在蒙托内罗的有用答案 https://stackoverflow.com/a/54289749/45375并改进了以下几个方面:

  • 控制递归深度
  • 提高性能
  • 与其他 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包含一个友好的、自动缩放的string大小的表示,而.Size是一个数字([long])包含实际字节数,这有助于进一步的编程处理。

注意:向输出对象添加属性以方便友好的显示这里只是为了实现方便才这样做。正确的 Powershell 方法是根据输出对象类型定义格式化指令 - 请参阅the docs https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_format.ps1xml.

Caveats(也适用于链接的答案):

  • Only logical报告大小,即文件所需的实际字节数data,这不同于磁盘上的大小,通常是larger,由于文件占用固定大小的块;相反,压缩文件和稀疏文件占用less磁盘空间。

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


Get-DirectorySize源代码

注意:需要 Windows PowerShell v3+;还兼容 PowerShellCore.

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).
#>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

列出给定结构中的所有文件夹和子文件夹以及文件大小 的相关文章

  • 需要 TensorFlow 依赖项。如何在 Windows 上运行 TensorFlow

    我有兴趣让 TensorFlow 在 Windows 上运行 但目前我意识到这是不可能的 因为某些依赖项无法在 Windows 上使用 例如巴泽尔 之所以出现这种需求 是因为据我目前了解 从 TensorFlow 访问 GPU 的唯一方法是
  • 如何从Windows阻止社交媒体[关闭]

    Closed 这个问题需要调试细节 help minimal reproducible example 目前不接受答案 我想根据时间阻止我的电脑上的社交媒体 晚上 9 点后屏蔽 上午 11 点后解锁 如家长控制 我尝试过关注但失败了 创建了
  • 检测 PowerShell 开关

    我正在用 C 开发 PowerShell cmdlet 并且有 true false switch 语句 我注意到 如果我希望 bool 为 true 我需要指定 SwitchName true 否则我会得到 Missing an argu
  • 为什么我只能用管理员权限才能导入Python中的某些模块?

    我正在努力解决 Python 2 7 中的一些奇怪问题 我写了一个很长的工具 在其中导入不同的模块 我必须首先使用它安装pip 该工具将在公司内部共享 不同的用户在其特定机器上拥有不同的权限 当另一个用户登录我的计算机 我在那里拥有管理员权
  • Powershell 新的 ScheduledTaskSettingsSet

    我尝试添加新的ScheduledTaskSettingsSet https technet microsoft com en us library jj649824 v wps 630 aspx具有自定义设置 根据 Technet 有可能的
  • teracopy 如何替换默认的 Windows 副本

    我问了这个问题Windows 文件复制内部结构 动态加密 https stackoverflow com questions 24220382 windows file copy internals on the fly encryptio
  • 常见的 Windows 编译器上有哪些 std::locale 名称可用?

    该标准对于什么构成有效的语言环境名称几乎没有提及 只有传递无效的区域设置名称才会导致std runtime error 哪些语言环境名称可用于常见的 Windows 编译器 例如 MSVC MinGW 和 ICC 好吧 C 和 C 语言环境
  • C# 控制台应用程序 - cmd.exe 挂起

    我在 Visual Studio 2013 中运行简单的 C 控制台应用程序时遇到问题 我的问题的详细信息 我成功运行控制台应用程序 默认的 按任意键继续 显示在最后 突然 它开始表现出不同的行为 并出现以下症状 一个新的命令窗口 cmd
  • 卸载以前的版本安装新版本的安装项目

    我创建了一个安装项目并安装在Windows系统中 在安装安装项目之前 我将其设置为 DetectNewInstallerVersion true and RemovePreviousVersion True 我也每次都换版本 但是 如果我重
  • 如何向未知用户目录读取/写入文件?

    我正在尝试从用户目录 C Users USERNAME Test Source 读取和写入文件 但我未能成功找到任何有关如何自动检测用户名的资源 其中的 USERNAME上面的例子 或者无论如何 我可以让它读取和写入目录 而不需要知道用户名
  • 关闭有效句柄时,AppVerifier 报告“无效句柄 - 代码 c0000008”

    我有一个简单的测试程序 在运行时会失败并出现异常AppVerifier 程序重复STD INPUT HANDLE然后尝试使用关闭它CloseHandle 该程序运行良好 无需AppVerifier返回TRUE for CloseHandle
  • 在 Win7 登录屏幕上运行应用程序[重复]

    这个问题在这里已经有答案了 我想通过服务在 Windows 7 的登录屏幕上运行应用程序 我对此进行了长期研究并尝试了不同的方法 但不幸的是到目前为止还没有完全成功 我设法在当前登录用户的锁定屏幕上运行该应用程序 起初我认为这就是我基本上试
  • 使用Powershell在断开的网卡上设置静态IP,可能吗?

    我需要在 Windows 10 上未连接到网络时设置网卡的 IP 地址 我试过了 Set NetIPAddress InterfaceAlias Ethernet IPAddress 192 168 5 10 PrefixLength 24
  • 用于创建计划任务的 VBScript

    我正在尝试创建一个 VBScript 它创建一个批处理文件 然后创建一个计划任务来运行该批处理文件 到目前为止 我尝试过的所有操作都创建了批处理文件 但没有创建计划任务 并且我没有收到任何错误 这是我到目前为止所拥有的 Option Exp
  • 如何在 WiX 中启动 PowerShell 并正确访问 Windows 注册表?

    Update 有趣的是 如果我运行 32 位 powershell 来运行脚本 它会给我同样的错误 看起来32位powershell无法访问64位注册表树 我尝试使用WixQuietExec64但它给出了同样的错误 我还尝试提供 power
  • 在 PowerShell 中过滤 TreeView 节点

    我的 TreeView 中有大量节点 并且有一个文本框可以过滤它们以突出显示匹配的搜索 然而 它有点混乱 因为它显示了所有其他节点 并且在我更改搜索后 它使所有节点都展开 我正在尝试做这样的事情 https www codeproject
  • 为什么我在 Windows 上使用 async 和 wait 时会收到 NotImplementedError 错误?

    我有这个代码 import os import time import asyncio async def run command args Example from http asyncio readthedocs io en lates
  • 在有或没有 UNICODE 支持的情况下,如何在我的程序中使用 _stprintf?

    微软的 定义 stprintf as swprintf if UNICODE被定义 并且sprintf如果不 但这些函数采用不同的参数 在swprintf 第二个参数是缓冲区大小 但是sprintf没有这个 有人偷懒了吗 如果是这样 这就是
  • 区分注册表项和值路径

    是否有相当于 System IO DirectoryInfo and System IO FileInfo 用于区分注册表项和值 我想评估一条路径并为用户记录该路径的最终目标是什么 到目前为止 这就是我所拥有的 而且有点丑陋 path Re
  • Microsoft Teams 中私人消息的传入 Webhook

    我可以从 C 应用程序或 PS 脚本创建传入 Webhook 将 JSON 消息发送到 MSFT 文档所解释的通道 但是 我想使用传入的 webhook 将 JSON 消息从我的应用程序发送到用户 作为私人消息 就像 Slack 允许的那样

随机推荐

  • Apache 缓存 javascript 资源?

    不久前我在使用 javascript 资源时遇到了麻烦 当我对它们进行更改时 它们不会生效 文件将变成无效的 javascript 萤火虫抛出错误和警告 我注意到我的更改没有出现 并且特殊字符被添加到文件末尾 再进一步挖掘 我注意到特殊字符
  • JavaScript 圆角透明背景

    我正在寻找一个可以在上面创建圆角的 JavaScript 库div具有透明背景的标签 使得父元素的背景颜色 图像在圆角处可见 以圆角为例without透明背景 看看左边的菜单这一页 http chaletsdesbouleaux com 请
  • Angular UI-Router 将根 url 发送到 404

    我有一个令人恼火的问题ui router 一切都按我想要的方式进行 所有错误的 URL 都会发送到404状态 但是 即使当 url 为时我的默认状态正确呈现 网址为 被重定向到 404 我怎样才能提供服务default向双方声明 and a
  • 更改 jquerymobile 上的自定义导航栏图标

    尚未找到更改具有多个页脚的页面上的自定义导航栏图标的解决方案 这就是我目前正在使用的 live menu ui icon css background url btn on gif important live menu ui icon c
  • 尝试在 for 循环中将元素添加到 xml 文件时出现 HIERARCHY_REQUEST_ERR

    正如标题所示 我尝试使用 for 循环将元素添加到 xml 文档中 我有一个ArrayList称为的字符串names我希望迭代 并为每个名称创建一个
  • 尝试打开 Pandas 时历史记录保存线程错误

    我刚刚在工作的远程桌面上安装了 IPython 我必须在桌面上创建一个快捷方式来连接到 IPython 因为远程桌面无法访问互联网 我能够成功打开 IPython 笔记本 但是 当我尝试导入 pandas 时 import pandas a
  • 如何测量执行的汇编指令的数量?

    我想以某种方式从二进制文件中获取 已执行的汇编程序指令的数量 考虑下面的代码 if password 0 p if password 1 a printf Correct Password n 那么如果我用例如启动程序 abc 它不会采用第
  • 迭代器不属于其分配的文本缓冲区

    这是一个简单的骨头save as 功能 gint save as GtkWidget parent struct buffers B GtkWidget file chooser gtk file chooser dialog new Sa
  • Javascript 模块模式、原型和 Google Closure

    我无法让此代码结构在 Google Closure 编译器的混淆中幸存下来 这是一些示例代码 var MyModule function function myModule Constructor function moduleFoo ur
  • 消除二值图像中的字符倾斜

    我正在研究车牌识别 问题是我必须消除二值图像中的字符倾斜 以提高模板匹配的准确性 我已经做了很多预处理来删除图像中不必要的像素 并且我可以将字符分割出来 但不幸的是 它们是倾斜的 从 转换为灰度到二进制 然后 预处理技术 分割后 从最后一张
  • XSLT:使用键和条件的“选择值”?

    这个问题是上一个线程的后续问题 XSLT 根据其他节点的值之和进行排序 https stackoverflow com questions 13502321 xslt sorting based on sum of values from
  • 如何在 App Engine 上免费运行应用程序

    我正在尝试在 Google App Engine 上运行 Parse Server 一个 Node js 应用程序 我正处于试用期 有 300 美元的免费信用 从这个页面开始 https cloud google com appengine
  • 将 Unity3d 与 Node.js 连接

    我正在尝试使用socket io 将我的unity3d 程序与node js 服务器连接 使用UnitySocketIO 我成功地建立了客户端和服务器之间的连接 但是 On 或 Emit 方法不起作用 有人可以帮我解决这个问题吗 void
  • 在 Matplotlib 中更改/删除轮廓线的透明度

    我正在使用轮廓绘制一些数据 但在设置透明度时遇到麻烦 我希望能够设置填充和线条的透明度 但似乎无法做到这一点 我的代码的简化版本如下 array np random rand 100 100 lonit and latit are lati
  • SQL - 如果满足使用多个先前列的条件,则 LAG 获取先前的值

    我有一个由以下人员创建的表 CREATE TABLE test table id INT EventName VARCHAR 50 HomeTeam VARCHAR 25 Metric INT INSERT INTO test table
  • 防止 AJAX 以字符串形式发送文件

    I have a file stored in this form imagesFile variable It contains file below 我想使用发送它FormData and AJAX 仅供参考 我正在使用 Vue 和 L
  • DDD:共享具有多个聚合根的实体

    学习DDD 在我们的应用程序中存在三个聚合根 不同类型的表单 所有这些都需要上传一些PDF 这些 pdf 上传附加了一些元数据 例如上传者和上传时间等 以便将它们存储在自己的表中 我的问题是这个 PDF 是否应该建模为值对象 实体或聚合根
  • 如何在 Azure AD B2C 中添加 b2c-extensions-app

    我使用经典的 Azure 门户创建了一些 B2C 目录 有时它会添加 b2c extensions app 但有时则不会 当我删除目录时 Azure 似乎有很长的内存 这阻止我尝试重新创建它 使用相同的名称 有没有办法手动添加 b2c ex
  • 如何防止浏览器阻止我创建的弹出窗口?

    我创建了一个简单的 JavaScript 函数来在加载后显示我的弹出窗口 但它一直被 Firefox 和 Google Chrome 阻止 我必须以某种方式在 Firefox 和 Chrome 上启用它才能显示弹出窗口 有其他选择吗 我在弹
  • 列出给定结构中的所有文件夹和子文件夹以及文件大小

    我试图列出光盘的文件夹结构和每个文件夹的大小 我已经确定了文件夹结构 现在我只需要输出每个文件夹的大小 根据https learn microsoft com en us windows server administration wind