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

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

# 统计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! 拿去不谢!

你可能感兴趣的:(Powershell,Windows,文本处理,c语言,java,spring)