统计C盘各种扩展名文件大小总和及数量的PowerShell脚本

本脚本只统计了一半文件的大小数量,其它部分系统文件无访问权限。需要在 TrustedInstaller 权限下运行才能访问。如何获取 TrustedInstaller 权限

Haskell 复制代码
# 统计C盘各种扩展名文件大小总和及数量的PowerShell脚本
$extSizes = @{}
$totalFiles = 0
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()

# 扫描文件并统计
Get-ChildItem -Path 'C:\' -File -Recurse -ErrorAction SilentlyContinue | ForEach-Object {
    $totalFiles++
    # 每处理5000个文件显示进度
    if ($totalFiles % 5000 -eq 0) {
        $elapsed = $stopwatch.Elapsed.ToString("mm\:ss")
        Write-Progress -Activity "扫描文件 (已处理 $totalFiles 个)" `
                       -Status "当前: $([System.IO.Path]::GetFileName($_.FullName))" `
                       -PercentComplete (($totalFiles % 100000)/1000)
    }
    
    $ext = $_.Extension.ToLower()
    if (-not $ext) { $ext = '_no_extension_' }
    
    if (-not $extSizes.ContainsKey($ext)) {
        $extSizes[$ext] = @{
            TotalSize = 0L
            Count = 0
        }
    }
    $extSizes[$ext].TotalSize += $_.Length
    $extSizes[$ext].Count++
}

# 转换大小格式的函数
function Format-FileSize {
    param([long]$size)
    switch ($size) {
        { $_ -ge 1TB } { return [math]::Round($_ / 1TB, 1).ToString('0.#') + "T" }
        { $_ -ge 1GB } { return [math]::Round($_ / 1GB, 1).ToString('0.#') + "G" }
        { $_ -ge 1MB } { return [math]::Round($_ / 1MB, 1).ToString('0.#') + "M" }
        { $_ -ge 1KB } { return [math]::Round($_ / 1KB, 1).ToString('0.#') + "K" }
        default { return "$_ B" }
    }
}

# 格式化数量显示(添加千位分隔符)
function Format-Count {
    param([int]$count)
    return $count.ToString("N0")
}

# 准备结果数据
$results = @()
foreach ($ext in $extSizes.Keys) {
    $results += [PSCustomObject]@{
        Extension = $ext
        Size      = Format-FileSize -size $extSizes[$ext].TotalSize
        Count     = Format-Count -count $extSizes[$ext].Count
        TotalBytes= $extSizes[$ext].TotalSize
    }
}

# 计算总扫描时间
$scanTime = $stopwatch.Elapsed.ToString("hh\:mm\:ss")

# 输出结果表格(按总大小降序)
$sortedResults = $results | Sort-Object TotalBytes -Descending

# 显示统计摘要
Clear-Host
Write-Host "`n文件扩展名统计报告 (C:\)" -ForegroundColor Cyan
Write-Host "扫描文件总数: $($totalFiles.ToString('N0'))" -ForegroundColor Yellow
Write-Host "扫描耗时: $scanTime" -ForegroundColor Yellow
Write-Host "发现扩展名类型: $($extSizes.Count)`n" -ForegroundColor Yellow

# 格式化表格输出
$sortedResults | Format-Table @(
    @{Label="扩展名"; Expression={$_.Extension}; Width=12; Alignment="Left"}
    @{Label="大小"; Expression={$_.Size}; Width=10; Alignment="Right"}
    @{Label="数量"; Expression={$_.Count}; Width=15; Alignment="Right"}
) -AutoSize

# 保存结果到CSV(修复数字扩展名问题)
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$csvPath = Join-Path -Path $env:TEMP -ChildPath "FileSizeSummary_$timestamp.csv"

# 创建CSV内容(修复数字扩展名问题)
$csvData = $sortedResults | ForEach-Object {
    # 在数字扩展名前添加单引号防止Excel转换
    $fixedExtension = if ($_.Extension -match '^\.\d+$') {
        "'" + $_.Extension
    } else {
        $_.Extension
    }
    
    [PSCustomObject]@{
        Extension = $fixedExtension
        Size      = $_.Size
        Count     = $_.Count
    }
}

$csvData | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8
Write-Host "`n结果已保存到: $csvPath" -ForegroundColor Green

# 额外提示Excel处理建议
Write-Host "`n注意: 数字扩展名(如 .1, .2)在CSV中已添加前缀单引号'" -ForegroundColor Magenta
Write-Host "在Excel中打开时请检查扩展名格式是否正确,若仍不正确请手动设置格式:" -ForegroundColor Magenta
Write-Host "1. 全选扩展名列" -ForegroundColor Yellow
Write-Host "2. 右键选择'设置单元格格式'" -ForegroundColor Yellow
Write-Host "3. 选择'文本'格式" -ForegroundColor Yellow

Read-Host "按 Enter 退出"

统计C盘各种扩展名文件大小总和及数量的PowerShell脚本

$extSizes = @{}

$totalFiles = 0

$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()

扫描文件并统计

Get-ChildItem -Path 'C:\' -File -Recurse -ErrorAction SilentlyContinue | ForEach-Object {

$totalFiles++

每处理5000个文件显示进度

if ($totalFiles % 5000 -eq 0) {

elapsed = stopwatch.Elapsed.ToString("mm\:ss")

Write-Progress -Activity "扫描文件 (已处理 $totalFiles 个)" `

-Status "当前: (\[System.IO.Path\]::GetFileName(_.FullName))" `

-PercentComplete (($totalFiles % 100000)/1000)

}

ext = _.Extension.ToLower()

if (-not ext) { ext = 'no_extension' }

if (-not extSizes.ContainsKey(ext)) {

extSizes\[ext] = @{

TotalSize = 0L

Count = 0

}

}

extSizes\[ext].TotalSize += $_.Length

extSizes\[ext].Count++

}

转换大小格式的函数

function Format-FileSize {

param([long]$size)

switch ($size) {

{ _ -ge 1TB } { return \[math\]::Round(_ / 1TB, 1).ToString('0.#') + "T" }

{ _ -ge 1GB } { return \[math\]::Round(_ / 1GB, 1).ToString('0.#') + "G" }

{ _ -ge 1MB } { return \[math\]::Round(_ / 1MB, 1).ToString('0.#') + "M" }

{ _ -ge 1KB } { return \[math\]::Round(_ / 1KB, 1).ToString('0.#') + "K" }

default { return "$_ B" }

}

}

格式化数量显示(添加千位分隔符)

function Format-Count {

param([int]$count)

return $count.ToString("N0")

}

准备结果数据

$results = @()

foreach (ext in extSizes.Keys) {

$results += [PSCustomObject]@{

Extension = $ext

Size = Format-FileSize -size extSizes\[ext].TotalSize

Count = Format-Count -count extSizes\[ext].Count

TotalBytes= extSizes\[ext].TotalSize

}

}

计算总扫描时间

scanTime = stopwatch.Elapsed.ToString("hh\:mm\:ss")

输出结果表格(按总大小降序)

sortedResults = results | Sort-Object TotalBytes -Descending

显示统计摘要

Clear-Host

Write-Host "`n文件扩展名统计报告 (C:\)" -ForegroundColor Cyan

Write-Host "扫描文件总数: (totalFiles.ToString('N0'))" -ForegroundColor Yellow

Write-Host "扫描耗时: $scanTime" -ForegroundColor Yellow

Write-Host "发现扩展名类型: (extSizes.Count)`n" -ForegroundColor Yellow

格式化表格输出

$sortedResults | Format-Table @(

@{Label="扩展名"; Expression={$_.Extension}; Width=12; Alignment="Left"}

@{Label="大小"; Expression={$_.Size}; Width=10; Alignment="Right"}

@{Label="数量"; Expression={$_.Count}; Width=15; Alignment="Right"}

) -AutoSize

保存结果到CSV(修复数字扩展名问题)

$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"

csvPath = Join-Path -Path env:TEMP -ChildPath "FileSizeSummary_$timestamp.csv"

创建CSV内容(修复数字扩展名问题)

csvData = sortedResults | ForEach-Object {

在数字扩展名前添加单引号防止Excel转换

fixedExtension = if (_.Extension -match '^\.\d+$') {

"'" + $_.Extension

} else {

$_.Extension

}

PSCustomObject\]@{ Extension = $fixedExtension Size = $_.Size Count = $_.Count } } $csvData \| Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8 Write-Host "\`n结果已保存到: $csvPath" -ForegroundColor Green # 额外提示Excel处理建议 Write-Host "\`n注意: 数字扩展名(如 .1, .2)在CSV中已添加前缀单引号'" -ForegroundColor Magenta Write-Host "在Excel中打开时请检查扩展名格式是否正确,若仍不正确请手动设置格式:" -ForegroundColor Magenta Write-Host "1. 全选扩展名列" -ForegroundColor Yellow Write-Host "2. 右键选择'设置单元格格式'" -ForegroundColor Yellow Write-Host "3. 选择'文本'格式" -ForegroundColor Yellow Read-Host "按 Enter 退出" 完全白嫖 DeepSeek! 拿去不谢!

相关推荐
毕设源码-邱学长28 分钟前
【开题答辩全过程】以 基于Java企业人事工资管理系统为例,包含答辩的问题和答案
java·开发语言
转转技术团队30 分钟前
回收系统架构演进实战:与Cursor结对扫清系统混沌
java·架构·cursor
AI分享猿31 分钟前
Java后端实战:SpringBoot接口遇异常请求,轻量WAF兼顾安全与性能
java·spring boot·安全
稚辉君.MCA_P8_Java41 分钟前
Gemini永久会员 Java中的四边形不等式优化
java·后端·算法
DKPT1 小时前
ZGC和G1收集器相比哪个更好?
java·jvm·笔记·学习·spring
n***F8751 小时前
修改表字段属性,SQL总结
java·数据库·sql
q***69771 小时前
【Spring Boot】统一数据返回
java·spring boot·后端
Hollis Chuang1 小时前
Spring Boot 4.0 正式发布,人麻了。。。
java·spring boot·后端·spring
Moshow郑锴1 小时前
实战分享:用 SpringBoot-API-Scheduler 构建 API 监控闭环 —— 从断言验证到智能警报
java·spring boot·后端·任务调度
无限进步_2 小时前
C语言动态内存的二维抽象:用malloc实现灵活的多维数组
c语言·开发语言·数据结构·git·算法·github·visual studio