scripts/Measure-DirectorySize.ps1
6.7 KB| 1 | #Requires -Version 7.0 |
| 2 | <# |
| 3 | .SYNOPSIS |
| 4 | 目录体积分析器:统计指定目录及其子目录占用的磁盘空间,找出最占空间的位置。 |
| 5 | |
| 6 | .DESCRIPTION |
| 7 | 只读工具,不删除、不移动任何文件。 |
| 8 | 默认按第一层子目录汇总大小,可按需要加深层级;可同时列出最大的单个文件。 |
| 9 | 支持把结果导出为 CSV 报告。 |
| 10 | |
| 11 | .PARAMETER Path |
| 12 | 要分析的目录路径。 |
| 13 | |
| 14 | .PARAMETER Depth |
| 15 | 统计到第几层子目录,默认 1(只看根目录下的直接子目录)。 |
| 16 | 某个目录的数值包含它下面所有子目录和文件的总和。 |
| 17 | |
| 18 | .PARAMETER Top |
| 19 | 每类结果显示多少条,默认 15。 |
| 20 | |
| 21 | .PARAMETER MinSizeMB |
| 22 | 只显示不小于该大小的目录(单位 MB),默认 0 表示全部显示。 |
| 23 | |
| 24 | .PARAMETER IncludeFiles |
| 25 | 同时列出体积最大的单个文件。 |
| 26 | |
| 27 | .PARAMETER ExportCsv |
| 28 | 把结果导出到指定 CSV 文件(UTF-8 带 BOM,Excel 可直接打开)。 |
| 29 | |
| 30 | .EXAMPLE |
| 31 | .\Measure-DirectorySize.ps1 -Path "D:\资料" |
| 32 | |
| 33 | .EXAMPLE |
| 34 | .\Measure-DirectorySize.ps1 -Path "D:\资料" -Depth 2 -Top 20 -IncludeFiles |
| 35 | |
| 36 | .EXAMPLE |
| 37 | .\Measure-DirectorySize.ps1 -Path "D:\资料" -MinSizeMB 100 -ExportCsv "D:\报告\目录体积.csv" |
| 38 | #> |
| 39 | [CmdletBinding()] |
| 40 | param( |
| 41 | [Parameter(Mandatory = $true, Position = 0)] |
| 42 | [string]$Path, |
| 43 | |
| 44 | [ValidateRange(1, 10)] |
| 45 | [int]$Depth = 1, |
| 46 | |
| 47 | [ValidateRange(1, 200)] |
| 48 | [int]$Top = 15, |
| 49 | |
| 50 | [double]$MinSizeMB = 0, |
| 51 | |
| 52 | [switch]$IncludeFiles, |
| 53 | |
| 54 | [string]$ExportCsv |
| 55 | ) |
| 56 | |
| 57 | function Format-Size { |
| 58 | param([Int64]$Bytes) |
| 59 | if ($Bytes -ge 1GB) { return ('{0:N2} GB' -f ($Bytes / 1GB)) } |
| 60 | if ($Bytes -ge 1MB) { return ('{0:N2} MB' -f ($Bytes / 1MB)) } |
| 61 | if ($Bytes -ge 1KB) { return ('{0:N1} KB' -f ($Bytes / 1KB)) } |
| 62 | return "$Bytes B" |
| 63 | } |
| 64 | |
| 65 | # ---------- 路径校验 ---------- |
| 66 | if (-not (Test-Path -LiteralPath $Path)) { |
| 67 | Write-Host "错误:路径不存在:$Path" |
| 68 | exit 2 |
| 69 | } |
| 70 | |
| 71 | $rootItem = Get-Item -LiteralPath $Path |
| 72 | if (-not $rootItem.PSIsContainer) { |
| 73 | Write-Host "错误:$Path 不是目录,本工具用于统计目录体积。" |
| 74 | exit 2 |
| 75 | } |
| 76 | |
| 77 | $root = $rootItem.FullName |
| 78 | Write-Host "正在扫描:$root" |
| 79 | $sw = [System.Diagnostics.Stopwatch]::StartNew() |
| 80 | |
| 81 | $scanErrors = $null |
| 82 | $files = @(Get-ChildItem -LiteralPath $root -Recurse -File -Force -ErrorAction SilentlyContinue -ErrorVariable scanErrors) |
| 83 | $sw.Stop() |
| 84 | |
| 85 | if ($files.Count -eq 0) { |
| 86 | Write-Host "提示:该目录下没有找到任何文件(也可能全部无访问权限)。" |
| 87 | exit 1 |
| 88 | } |
| 89 | |
| 90 | $errorCount = 0 |
| 91 | if ($scanErrors) { $errorCount = @($scanErrors).Count } |
| 92 | |
| 93 | # ---------- 汇总 ---------- |
| 94 | $totalSize = [Int64]0 |
| 95 | foreach ($f in $files) { $totalSize += $f.Length } |
| 96 | |
| 97 | $units = @{} |
| 98 | $dirSet = New-Object 'System.Collections.Generic.HashSet[string]' |
| 99 | |
| 100 | foreach ($f in $files) { |
| 101 | [void]$dirSet.Add($f.DirectoryName) |
| 102 | |
| 103 | $rel = [System.IO.Path]::GetRelativePath($root, $f.DirectoryName) |
| 104 | if ($rel -eq '.' -or $rel -eq [string]::Empty) { |
| 105 | # 直接放在根目录下的文件,单独归为一类 |
| 106 | $unit = $root |
| 107 | if (-not $units.ContainsKey($unit)) { $units[$unit] = [Int64]0 } |
| 108 | $units[$unit] = $units[$unit] + $f.Length |
| 109 | continue |
| 110 | } |
| 111 | |
| 112 | # 文件的每一级祖先目录都累加,父目录数值包含其全部子目录 |
| 113 | $sep = [string][System.IO.Path]::DirectorySeparatorChar |
| 114 | $sepChars = [char[]]@([System.IO.Path]::DirectorySeparatorChar) |
| 115 | $parts = $rel.Split($sepChars) |
| 116 | $take = [Math]::Min($Depth, $parts.Count) |
| 117 | for ($i = 1; $i -le $take; $i++) { |
| 118 | $sub = ($parts[0..($i - 1)]) -join $sep |
| 119 | $unit = Join-Path $root $sub |
| 120 | if (-not $units.ContainsKey($unit)) { $units[$unit] = [Int64]0 } |
| 121 | $units[$unit] = $units[$unit] + $f.Length |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | # ---------- 输出 ---------- |
| 126 | Write-Host '' |
| 127 | Write-Host "=== 总览 ===" |
| 128 | Write-Host ("根目录:{0}" -f $root) |
| 129 | Write-Host ("总大小:{0} 文件数:{1} 目录数:{2}" -f (Format-Size $totalSize), $files.Count, $dirSet.Count) |
| 130 | Write-Host ("扫描耗时:{0:N1} 秒" -f $sw.Elapsed.TotalSeconds) |
| 131 | if ($errorCount -gt 0) { |
| 132 | Write-Host ("提示:有 {0} 处因权限或占用被跳过,统计结果可能略小于实际占用。" -f $errorCount) |
| 133 | } |
| 134 | |
| 135 | $minBytes = [Int64]($MinSizeMB * 1MB) |
| 136 | |
| 137 | $dirRows = @() |
| 138 | foreach ($k in $units.Keys) { |
| 139 | if ($units[$k] -lt $minBytes) { continue } |
| 140 | $shownPath = [System.IO.Path]::GetRelativePath($root, $k) |
| 141 | if ($shownPath -eq '.') { $shownPath = '(根目录下的文件)' } |
| 142 | $dirRows += [PSCustomObject]@{ |
| 143 | Path = $shownPath |
| 144 | Size = $units[$k] |
| 145 | Share = if ($totalSize -gt 0) { [Math]::Round($units[$k] / $totalSize * 100, 1) } else { 0 } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | Write-Host '' |
| 150 | Write-Host ("=== 体积最大的 {0} 个目录(第 {1} 层) ===" -f $Top, $Depth) |
| 151 | if ($dirRows.Count -eq 0) { |
| 152 | Write-Host '没有满足条件的目录。' |
| 153 | } |
| 154 | else { |
| 155 | $dirRows | |
| 156 | Sort-Object -Property Size -Descending | |
| 157 | Select-Object -First $Top | |
| 158 | ForEach-Object { |
| 159 | Write-Host ("{0,10} {1,6}% {2}" -f (Format-Size $_.Size), $_.Share, $_.Path) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | $fileRows = @() |
| 164 | if ($IncludeFiles) { |
| 165 | $fileRows = $files | |
| 166 | Sort-Object -Property Length -Descending | |
| 167 | Select-Object -First $Top | |
| 168 | ForEach-Object { |
| 169 | [PSCustomObject]@{ |
| 170 | Path = [System.IO.Path]::GetRelativePath($root, $_.FullName) |
| 171 | Size = $_.Length |
| 172 | Share = if ($totalSize -gt 0) { [Math]::Round($_.Length / $totalSize * 100, 1) } else { 0 } |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | Write-Host '' |
| 177 | Write-Host ("=== 体积最大的 {0} 个文件 ===" -f $Top) |
| 178 | foreach ($r in $fileRows) { |
| 179 | Write-Host ("{0,10} {1,6}% {2}" -f (Format-Size $r.Size), $r.Share, $r.Path) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | # ---------- 导出 ---------- |
| 184 | if ($ExportCsv) { |
| 185 | $allRows = @() |
| 186 | foreach ($r in ($dirRows | Sort-Object -Property Size -Descending)) { |
| 187 | $allRows += [PSCustomObject]@{ 类型 = '目录'; 相对路径 = $r.Path; 字节 = $r.Size; 占比 = "$($r.Share)%" } |
| 188 | } |
| 189 | foreach ($r in $fileRows) { |
| 190 | $allRows += [PSCustomObject]@{ 类型 = '文件'; 相对路径 = $r.Path; 字节 = $r.Size; 占比 = "$($r.Share)%" } |
| 191 | } |
| 192 | |
| 193 | try { |
| 194 | $csvFull = [System.IO.Path]::GetFullPath($ExportCsv) |
| 195 | $csvDir = [System.IO.Path]::GetDirectoryName($csvFull) |
| 196 | if ($csvDir -and -not (Test-Path -LiteralPath $csvDir)) { |
| 197 | New-Item -ItemType Directory -Force -Path $csvDir | Out-Null |
| 198 | } |
| 199 | $allRows | Export-Csv -LiteralPath $csvFull -NoTypeInformation -Encoding utf8BOM |
| 200 | Write-Host '' |
| 201 | Write-Host "报告已导出:$csvFull" |
| 202 | } |
| 203 | catch { |
| 204 | Write-Host ("导出失败:{0}" -f $_.Exception.Message) |
| 205 | exit 3 |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | Write-Host '' |
| 210 | Write-Host '说明:本工具只读取文件信息,不会删除或移动任何东西。' |
| 211 | exit 0 |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

