worxfr头像

Windows C盘空间分析神器:安全智能的磁盘清理助手

🎯 项目简介

一个基于 PowerShell 的 C 盘空间分析工具,专为开发者设计。它能智能扫描系统中的各类缓存目录,按大小和安全等级分类展示,只分析不删除,让你明明白白地清理磁盘。

✨ 核心特性

  • 🔍 预置 20+ 常见缓存路径 - Docker、Node、Maven、Chrome 等一网打尽
  • 🛡️ 双层安全防护 - 通配符黑名单 + 正则表达式,绝不误删系统文件
  • 📊 多维度分类 - 按类型、大小、安全级别智能排序
  • 📄 HTML 报告导出 - 支持生成可视化分析报告
  • 🎨 分类着色显示 - 安全/谨慎项目一目了然

在这里插入图片描述


🚀 快速上手

基础使用

# 1. 右键"以管理员身份运行" PowerShell

# 2. 基础扫描
.\CleanC.ps1

# 3. 显示详细子目录
.\CleanC.ps1 -ShowDetails

# 4. 导出HTML报告
.\CleanC.ps1 -ExportHTML report.html

运行示例输出

=== C盘空间分析工具 ===

[开发工具] 🐳 Docker 数据
  路径: C:\Users\YourName\AppData\Local\Docker\wsl\data
  大小: 25.6 GB
  级别: ⚠️ 谨慎清理
  说明: Docker Desktop WSL2 镜像数据
  建议: 可能占用几十GB,建议用 docker system prune 清理

[开发工具] 💚 Node.js 缓存
  路径: C:\Users\YourName\AppData\Roaming\npm-cache
  大小: 3.2 GB
  级别: ✅ 安全清理
  说明: npm 包缓存,可安全删除
  建议: 删除后首次 npm install 会慢一些

总计: 28.8 GB 可清理空间

⚙️ 配置详解

1. 预置扫描目录

脚本内置 5 大类清理目标:

类别包含项目典型占用
🛠️ 开发工具Docker、npm、Maven、Gradle、pip、JetBrains5-50GB
🌐 浏览器Chrome、Edge、Firefox 缓存500MB-2GB
🗑️ 系统临时Windows Temp、用户临时、Update缓存1-5GB
💻 IDE/编辑器VS、Android Studio、.NET 包1-10GB
📱 应用数据微信、QQ、下载文件夹1-10GB

2. 黑名单保护机制

通配符黑名单(快速匹配)
$PathBlacklist = @(
    "C:\Windows\System32",         # 系统核心
    "*\System32\*",                # 路径关键词
    "*iconcache*",                 # 缩略图数据库
    "*System Volume Information*", # 系统卷信息
    "*\WindowsApps\*"              # UWP 应用
)
正则黑名单(高级匹配)
$PathBlacklistRegex = @(
    "\\(drivers?|DriverStore)\\",      # 驱动文件
    "\\(System32|SysWOW64)\\.*\.(sys|dll)$",  # 系统库
    "thumbcache_\d+\.db$"              # 缩略图数据库
)

3. 自定义扫描目标

@{
    Name = "自定义缓存"
    Paths = @("C:\Users\*\YourApp\Cache")
    Depth = 2                    # 扫描深度
    MinSize = 100MB              # 最小显示阈值
    SafeLevel = "安全"           # 安全/谨慎
    Category = "应用"            # 分类
    Description = "说明文字"
    Tips = "清理建议"
    Icon = "🎯"                  # 图标(可选)
}

🛡️ 安全级别说明

级别图标含义示例
✅ 安全清理绿色纯缓存,删除后自动重建npm-cache、浏览器缓存、Temp
⚠️ 谨慎清理黄色可能含用户数据或配置Docker数据、Maven仓库、微信缓存

📋 清理前检查清单

建议操作流程

1. ✅ 关闭相关程序(浏览器、IDE、Docker等)
2. ✅ 运行脚本扫描分析
3. ✅ 记录"谨慎清理"项目的路径
4. ✅ 手动打开文件夹确认内容
5. ✅ 选择性删除不需要的文件
6. ✅ 重启应用验证功能正常

⚠️ 特别注意

目录注意事项
Docker 数据用 docker system prune -a 而非直接删除文件
Maven 仓库本地 install 的包删除后需重新构建
下载文件夹可能有重要安装包或文档
微信缓存可能包含聊天记录中的图片

🎨 HTML 报告功能

导出的 HTML 报告包含:

  • 📊 可交互的数据表格
  • 🎯 按类别/大小排序
  • 🌈 可视化饼图(占用分布)
  • 📱 响应式设计,支持手机查看

💡 进阶技巧

1. 定期任务

# 每周自动生成报告
schtasks /create /tn "C盘分析" /tr "powershell C:\Scripts\CleanC.ps1 -ExportHTML C:\Reports\disk_$(Get-Date -f 'yyyyMMdd').html" /sc weekly

2. 命令行清理组合

# npm + yarn + pnpm 一键清理
npm cache clean --force && yarn cache clean && pnpm store prune

# Docker 完整清理
docker system prune -a --volumes

# Gradle 清理
gradle cleanBuildCache

🔧 故障排查

Q: 提示"拒绝访问"?
A: 需要管理员权限运行 PowerShell

Q: 扫描很慢?
A: 减少 Depth 参数或增大 MinSize 阈值

Q: 某些路径显示 0 字节?
A: 可能被系统权限保护,或已包含在黑名单中


📝 总结

这个脚本帮你:

  • ✅ 看清楚 - 哪些目录占用空间大
  • ✅ 选明白 - 哪些可以安全删除
  • ✅ 删干净 - 一次释放几十GB空间

记住:这不是自动清理工具,而是你的专业分析助手 🎯


定期使用,让 C 盘永远保持健康状态!

# -*- coding: utf-8-with-bom -*-
# PowerShell Script Encoding: UTF-8-BOM
# 如遇到编码问题,请使用 Notepad++ 将文件转换为 UTF-8-BOM 编码

<#
.SYNOPSIS
    C盘空间分析工具 - 扫描并展示大文件夹,辅助用户清理

.DESCRIPTION
    扫描预制的缓存目录,按大小和安全等级分类展示
    只读分析,不执行删除操作,由用户自行决定清理

.AUTHOR
    AI Assistant

.VERSION
    1.0

.EXAMPLE
    # 基础使用 - 扫描并显示可清理项目
    .\CleanC.ps1

.EXAMPLE
    # 显示详细子目录信息
    .\CleanC.ps1 -ShowDetails

.EXAMPLE
    # 直接导出HTML报告
    .\CleanC.ps1 -ExportHTML report.html

.NOTES
    使用前建议:
    1. 右键点击 PowerShell 图标,选择"以管理员身份运行"
    2. 执行脚本进行扫描分析
    3. 确认后手动清理建议的目录
    
    清理级别说明:
    - 安全清理:可放心删除,下次使用时会自动重建
    - 谨慎清理:建议检查内容后再删除,可能包含配置或本地数据
#>

param(
    [string]$ExportHTML = "",  # 导出HTML报告路径
    [switch]$ShowDetails = $false  # 显示详细子目录
)

# ============================================
# 黑名单配置区域 - 支持正则表达式
# ============================================

$PathBlacklist = @(
    # 系统关键目录(精确匹配)
    "C:\Windows\System32",
    "C:\Windows\SysWOW64",
    "C:\Program Files\Windows",
    "C:\ProgramData\Microsoft\Windows\Start Menu",
    
    # 路径关键词(模糊匹配)
    "*\System32\*",
    "*\SysWOW64\*",
    "*\WinSxS\*",
    "*\Boot\*",
    "*\Recovery\*",
    "*\Windows Defender\*",
    "*\Windows Security\*",
    
    # 缩略图和图标缓存
    "*iconcache*",
    "*thumbcache*",
    "*\Windows\Explorer\*",
    "*\Microsoft\Windows\INetCache\*",
    
    # 系统保护文件
    "*System Volume Information*",
    "*`$Recycle.Bin*",
    "*pagefile.sys*",
    "*hiberfil.sys*",
    "*swapfile.sys*",
    
    # 危险的用户配置
    "*\WindowsApps\*",
    "*\SystemApps\*",
    "*\Windows\Installer\*"
)

# 正则表达式黑名单(高级匹配)
$PathBlacklistRegex = @(
    # 匹配所有系统驱动相关
    "\\(drivers?|DriverStore)\\",
    
    # 匹配所有.sys/.dll在System32/SysWOW64
    "\\(System32|SysWOW64)\\.*\.(sys|dll)$",
    
    # 匹配Windows内置应用
    "\\WindowsApps\\Microsoft\.",
    
    # 匹配系统备份和还原点
    "\\System Volume Information\\",
    
    # 匹配所有缩略图数据库
    "thumbcache_\d+\.db$",
    "iconcache_\d+\.db$"
)

# ============================================
# 配置区域
# ============================================
$PresetFolders = @(
    # ========== 开发工具缓存 ==========
    
    @{
        Name = "Docker 数据"
        Paths = @(
            "C:\Users\*\AppData\Local\Docker\wsl\data"
        )
        Depth = 1
        MinSize = 1GB
        SafeLevel = "谨慎"
        Category = "开发工具"
        Description = "Docker Desktop WSL2 镜像数据"
        Tips = "可能占用几十GB,建议用 docker system prune 清理"
        Icon = "🐳"
    },
    
    @{
        Name = "Yarn 缓存"
        Paths = @(
            "C:\Users\*\AppData\Local\Yarn\Cache",
            "C:\Users\*\.yarn\berry\cache"
        )
        Depth = 2
        MinSize = 100MB
        SafeLevel = "安全"
        Category = "开发工具"
        Description = "Yarn 包管理器缓存"
        Tips = "可用 yarn cache clean 清理"
        Icon = "📦"
    },
    
    @{
        Name = "pnpm 缓存"
        Paths = @(
            "C:\Users\*\AppData\Local\pnpm\store",
            "C:\Users\*\.pnpm-store"
        )
        Depth = 2
        MinSize = 200MB
        SafeLevel = "安全"
        Category = "开发工具"
        Description = "pnpm 包管理器存储"
        Tips = "可用 pnpm store prune 清理"
        Icon = "📦"
    },
    
    @{
        Name = "Node.js 缓存"
        Paths = @(
            "C:\Users\*\AppData\Roaming\npm-cache",
            "C:\Users\*\AppData\Local\npm-cache",
            "C:\Users\*\.npm"
        )
        Depth = 2
        MinSize = 100MB
        SafeLevel = "安全"
        Category = "开发工具"
        Description = "npm 包缓存,可安全删除,下次使用会自动重建"
        Tips = "删除后首次 npm install 会慢一些"
        Icon = "💚"
    },
    
    @{
        Name = "Gradle 缓存"
        Paths = @(
            "C:\Users\*\.gradle\caches",
            "C:\Users\*\.gradle\wrapper"
        )
        Depth = 3
        MinSize = 200MB
        SafeLevel = "安全"
        Category = "开发工具"
        Description = "Android/Java 项目构建缓存"
        Tips = "删除后首次构建会重新下载依赖"
        Icon = "🐘"
    },
    
    @{
        Name = "Maven 仓库"
        Paths = @(
            "C:\Users\*\.m2\repository"
        )
        Depth = 4
        MinSize = 500MB
        SafeLevel = "谨慎"
        Category = "开发工具"
        Description = "Java Maven 依赖库"
        Tips = "如果有本地开发的库,删除后需重新 install"
        Icon = "☕"
    },
    
    @{
        Name = "Python pip 缓存"
        Paths = @(
            "C:\Users\*\AppData\Local\pip\cache",
            "C:\Users\*\.cache\pip"
        )
        Depth = 2
        MinSize = 100MB
        SafeLevel = "安全"
        Category = "开发工具"
        Description = "Python 包安装缓存"
        Tips = "删除后需重新下载包"
        Icon = "🐍"
    },
    
    @{
        Name = "JetBrains IDE 缓存"
        Paths = @(
            "C:\Users\*\AppData\Local\JetBrains\*\cache",
            "C:\Users\*\AppData\Local\JetBrains\*\caches",
            "C:\Users\*\.IntelliJIdea*\system\caches",
            "C:\Users\*\.PyCharm*\system\caches",
            "C:\Users\*\.WebStorm*\system\caches"
        )
        Depth = 2
        MinSize = 200MB
        SafeLevel = "安全"
        Category = "开发工具"
        Description = "IDEA/PyCharm/WebStorm 等 IDE 的索引缓存"
        Tips = "删除后首次打开项目会重新索引"
        Icon = "🧠"
    },
    
    @{
        Name = "Go modules 缓存"
        Paths = @(
            "C:\Users\*\go\pkg\mod\cache"
        )
        Depth = 2
        MinSize = 100MB
        SafeLevel = "安全"
        Category = "开发工具"
        Description = "Go 模块下载缓存"
        Icon = "🐹"
    },
    
    @{
        Name = "Rust Cargo 缓存"
        Paths = @(
            "C:\Users\*\.cargo\registry\cache",
            "C:\Users\*\.cargo\git\checkouts"
        )
        Depth = 2
        MinSize = 100MB
        SafeLevel = "安全"
        Category = "开发工具"
        Description = "Rust 包管理器缓存"
        Icon = "🦀"
    },
    
    # ========== 浏览器缓存 ==========
    @{
        Name = "Chrome 缓存"
        Paths = @(
            "C:\Users\*\AppData\Local\Google\Chrome\User Data\*\Cache",
            "C:\Users\*\AppData\Local\Google\Chrome\User Data\*\Code Cache",
            "C:\Users\*\AppData\Local\Google\Chrome\User Data\*\GPUCache"
        )
        Depth = 1
        MinSize = 200MB
        SafeLevel = "安全"
        Category = "浏览器"
        Description = "Chrome 网页缓存,可显著释放空间"
        Tips = "删除后浏览器首次加载网页会稍慢"
        Icon = "🌐"
    },
    
    @{
        Name = "Edge 缓存"
        Paths = @(
            "C:\Users\*\AppData\Local\Microsoft\Edge\User Data\*\Cache",
            "C:\Users\*\AppData\Local\Microsoft\Edge\User Data\*\Code Cache",
            "C:\Users\*\AppData\Local\Microsoft\Edge\User Data\*\GPUCache"
        )
        Depth = 1
        MinSize = 200MB
        SafeLevel = "安全"
        Category = "浏览器"
        Description = "Edge 浏览器缓存"
        Icon = "🔷"
    },
    
    @{
        Name = "Firefox 缓存"
        Paths = @(
            "C:\Users\*\AppData\Local\Mozilla\Firefox\Profiles\*\cache2",
            "C:\Users\*\AppData\Local\Mozilla\Firefox\Profiles\*\startupCache"
        )
        Depth = 1
        MinSize = 200MB
        SafeLevel = "安全"
        Category = "浏览器"
        Description = "Firefox 浏览器缓存"
        Icon = "🦊"
    },
    
    # ========== 系统临时文件 ==========
    @{
        Name = "下载文件夹"
        Paths = @(
            "C:\Users\*\Downloads"
        )
        Depth = 2
        MinSize = 500MB
        SafeLevel = "谨慎"
        Category = "用户数据"
        Description = "下载目录,常堆积安装包和临时文件"
        Tips = "已安装的软件安装包通常可删除"
        Icon = "📥"
    },
    
    @{
        Name = "Windows 临时文件"
        Paths = @(
            "C:\Windows\Temp"
        )
        Depth = 2
        MinSize = 50MB
        SafeLevel = "安全"
        Category = "系统"
        Description = "系统临时文件夹"
        Tips = "删除时可能提示文件占用,跳过即可"
        Icon = "🗑️"
    },
    
    @{
        Name = "用户临时文件"
        Paths = @(
            "C:\Users\*\AppData\Local\Temp"
        )
        Depth = 2
        MinSize = 100MB
        SafeLevel = "安全"
        Category = "系统"
        Description = "用户临时文件,安装程序、解压缓存等"
        Icon = "📂"
    },
    
    @{
        Name = "Windows Update 缓存"
        Paths = @(
            "C:\Windows\SoftwareDistribution\Download"
        )
        Depth = 2
        MinSize = 200MB
        SafeLevel = "安全"
        Category = "系统"
        Description = "Windows 更新下载缓存"
        Tips = "删除后 Windows Update 需重新下载补丁"
        Icon = "🔄"
    },
    
    @{
        Name = "Windows 日志"
        Paths = @(
            "C:\Windows\Logs",
            "C:\Windows\Panther"
        )
        Depth = 2
        MinSize = 50MB
        SafeLevel = "谨慎"
        Category = "系统"
        Description = "系统安装和更新日志"
        Tips = "排查系统问题时可能需要"
        Icon = "📋"
    },
    
    # ========== 应用缓存 ==========
    @{
        Name = "Visual Studio 缓存"
        Paths = @(
            "C:\Users\*\AppData\Local\Microsoft\VisualStudio\*\ComponentModelCache",
            "C:\Users\*\.nuget\packages"
        )
        Depth = 2
        MinSize = 500MB
        SafeLevel = "谨慎"
        Category = "应用"
        Description = "VS 组件缓存和 NuGet 包"
        Tips = "NuGet 包可能包含项目依赖"
        Icon = "🟣"
    },
    
    @{
        Name = "Android Studio 缓存"
        Paths = @(
            "C:\Users\*\.android\build-cache",
            "C:\Users\*\.android\cache"
        )
        Depth = 2
        MinSize = 200MB
        SafeLevel = "安全"
        Category = "开发工具"
        Description = "Android 构建缓存"
        Icon = "🤖"
    },
    
    @{
        Name = "微信缓存"
        Paths = @(
            "C:\Users\*\Documents\WeChat Files\*\FileStorage\Cache",
            "C:\Users\*\Documents\WeChat Files\*\Applet"
        )
        Depth = 2
        MinSize = 200MB
        SafeLevel = "谨慎"
        Category = "应用"
        Description = "微信缓存和小程序数据"
        Tips = "可能包含聊天图片等,建议手动清理"
        Icon = "💬"
    },
    
    @{
        Name = "QQ缓存"
        Paths = @(
            "C:\Users\*\Documents\Tencent Files\*\Image\C2C",
            "C:\Users\*\Documents\Tencent Files\*\FileRecv"
        )
        Depth = 2
        MinSize = 200MB
        SafeLevel = "谨慎"
        Category = "应用"
        Description = "QQ 图片和文件缓存"
        Tips = "可能包含重要文件,建议手动清理"
        Icon = "🐧"
    },
    
    @{
        Name = "百度网盘下载"
        Paths = @(
            "C:\Users\*\BaiduNetdiskDownload"
        )
        Depth = 1
        MinSize = 1GB
        SafeLevel = "谨慎"
        Category = "应用"
        Description = "百度网盘默认下载位置"
        Tips = "检查是否有已处理完的文件"
        Icon = "☁️"
    },
    
    @{
        Name = "迅雷下载"
        Paths = @(
            "C:\Users\*\Downloads\Thunder",
            "C:\迅雷下载"
        )
        Depth = 1
        MinSize = 1GB
        SafeLevel = "谨慎"
        Category = "应用"
        Description = "迅雷默认下载位置"
        Tips = "检查是否有已处理完的文件"
        Icon = "⚡"
    }
)

# ============================================
# 辅助函数
# ============================================

function Test-PathInBlacklist {
    param([string]$Path)
    
    # 1. 通配符黑名单检查
    foreach ($pattern in $PathBlacklist) {
        if ($Path -like $pattern) {
            return $true
        }
    }
    
    # 2. 正则表达式黑名单检查[来源6](https://www.reddit.com/r/PowerShell/comments/rktm1m/regex_filter_against_array/?tl=zh-hans) [来源7](http://www.splaybow.com/post/powershell-resolve-relative-path.html) [来源8](https://blog.csdn.net/itanders/article/details/79605984) 
    foreach ($regex in $PathBlacklistRegex) {
        if ($Path -match $regex) {
            return $true
        }
    }
    
    return $false
}

function Format-FileSize {
    param([long]$Size)
    
    if ($Size -ge 1TB) { return "{0:N2} TB" -f ($Size / 1TB) }
    if ($Size -ge 1GB) { return "{0:N2} GB" -f ($Size / 1GB) }
    if ($Size -ge 1MB) { return "{0:N2} MB" -f ($Size / 1MB) }
    if ($Size -ge 1KB) { return "{0:N2} KB" -f ($Size / 1KB) }
    return "$Size B"
}

function Get-FolderSize {
    param(
        [string]$Path,
        [int]$MaxDepth = 0,
        [int]$CurrentDepth = 0
    )
    
    if (-not (Test-Path $Path)) {
        return $null
    }
    
    try {
        $size = 0
        $subFolders = @()
        
        # 计算当前目录文件大小
        Get-ChildItem -Path $Path -File -ErrorAction SilentlyContinue | ForEach-Object {
            $size += $_.Length
        }
        
        # 如果未达到最大深度,递归子文件夹
        if ($MaxDepth -eq 0 -or $CurrentDepth -lt $MaxDepth) {
            Get-ChildItem -Path $Path -Directory -ErrorAction SilentlyContinue | ForEach-Object {
                $subResult = Get-FolderSize -Path $_.FullName -MaxDepth $MaxDepth -CurrentDepth ($CurrentDepth + 1)
                if ($subResult) {
                    $size += $subResult.Size
                    if ($MaxDepth -gt 0 -and $CurrentDepth -eq $MaxDepth - 1) {
                        $subFolders += @{
                            Path = $_.FullName
                            Size = $subResult.Size
                        }
                    }
                }
            }
        }
        
        return @{
            Size = $size
            SubFolders = $subFolders
        }
    }
    catch {
        return $null
    }
}

function Expand-PathWithWildcard {
    param([string]$PathPattern)
    
    $expandedPaths = @()
    
    # 处理通配符
    try {
        $resolvedPaths = Resolve-Path $PathPattern -ErrorAction SilentlyContinue
        if ($resolvedPaths) {
            $expandedPaths += $resolvedPaths | ForEach-Object { $_.Path }
        }
    }
    catch {
        # 路径不存在,忽略
    }
    
    return $expandedPaths
}

# ============================================
# 主扫描函数
# ============================================

function Start-DiskScan {
    Write-Host "`n========================================" -ForegroundColor Cyan
    Write-Host "     C盘空间分析工具 v1.0" -ForegroundColor Cyan
    Write-Host "========================================`n" -ForegroundColor Cyan
    
    Write-Host "? 开始扫描预制目录..." -ForegroundColor Yellow
    Write-Host "   提示:扫描过程可能需要几分钟,请耐心等待`n" -ForegroundColor Gray
    
    $results = @()
    $totalScanned = 0
    $totalFound = 0
    
    foreach ($preset in $PresetFolders) {
        $totalScanned++
        Write-Progress -Activity "扫描中" -Status "$($preset.Name)" -PercentComplete (($totalScanned / $PresetFolders.Count) * 100)
        
        foreach ($pathPattern in $preset.Paths) {
            $expandedPaths = Expand-PathWithWildcard -PathPattern $pathPattern
            
            foreach ($path in $expandedPaths) {
                if (Test-Path $path) {
					# 黑名单检查
					if (Test-PathInBlacklist -Path $path) {
						Write-Host "  ⛔ 已跳过(系统保护): $path" -ForegroundColor DarkRed
						continue
					}

                    Write-Host "  ?? 扫描: $path" -ForegroundColor DarkGray
                    
                    $scanResult = Get-FolderSize -Path $path -MaxDepth $preset.Depth
                    
                    if ($scanResult -and $scanResult.Size -ge $preset.MinSize) {
                        $totalFound++
                        
                        $result = [PSCustomObject]@{
                            Name = $preset.Name
                            Icon = $preset.Icon
                            Category = $preset.Category
                            Path = $path
                            Size = $scanResult.Size
                            SizeFormatted = Format-FileSize -Size $scanResult.Size
                            SafeLevel = $preset.SafeLevel
                            Description = $preset.Description
                            Tips = $preset.Tips
                            SubFolders = $scanResult.SubFolders
                        }
                        
                        $results += $result
                        
                        Write-Host "     ? 发现: $($result.SizeFormatted)" -ForegroundColor Green
                    }
                }
            }
        }
    }
    
    Write-Progress -Activity "扫描中" -Completed
    
    Write-Host "`n? 扫描完成!" -ForegroundColor Green
    Write-Host "   已扫描 $totalScanned 个类型,发现 $totalFound 个可清理项目`n" -ForegroundColor Gray
    
    return $results
}

# ============================================
# 结果展示函数
# ============================================

function Show-ScanResults {
    param([array]$Results)
    
    if ($Results.Count -eq 0) {
        Write-Host "`n? 恭喜!未发现大型缓存文件夹" -ForegroundColor Green
        Write-Host "   您的C盘相当整洁!`n" -ForegroundColor Gray
        return
    }
    
    # 按类别和安全等级分组
    $safeItems = $Results | Where-Object { $_.SafeLevel -eq "安全" } | Sort-Object Size -Descending
    $cautiousItems = $Results | Where-Object { $_.SafeLevel -eq "谨慎" } | Sort-Object Size -Descending
    
    # 计算总大小
    $totalSafeSize = ($safeItems | Measure-Object -Property Size -Sum).Sum
    $totalCautiousSize = ($cautiousItems | Measure-Object -Property Size -Sum).Sum
    $totalSize = $totalSafeSize + $totalCautiousSize
    
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "         清理建议报告" -ForegroundColor Cyan
    Write-Host "========================================`n" -ForegroundColor Cyan
    
    # 显示安全清理项
    if ($safeItems.Count -gt 0) {
        Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Green
        Write-Host "  ? 【安全清理】 可放心删除" -ForegroundColor Green
        Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Green
        Write-Host "  这些缓存可安全删除,下次使用时会自动重建`n" -ForegroundColor Gray
        
        $index = 1
        foreach ($item in $safeItems) {
            Write-Host "  [$index] $($item.Icon) $($item.Name)" -ForegroundColor White
            Write-Host "      大小: " -NoNewline -ForegroundColor Gray
            Write-Host "$($item.SizeFormatted)" -ForegroundColor Yellow
            Write-Host "      路径: " -NoNewline -ForegroundColor Gray
            Write-Host "$($item.Path)" -ForegroundColor Cyan
            Write-Host "      说明: $($item.Description)" -ForegroundColor DarkGray
            
            if ($item.Tips) {
                Write-Host "      提示: $($item.Tips)" -ForegroundColor DarkYellow
            }
            
            # 显示子文件夹详情
            if ($ShowDetails -and $item.SubFolders -and $item.SubFolders.Count -gt 0) {
                Write-Host "      子目录:" -ForegroundColor Gray
                $item.SubFolders | Sort-Object Size -Descending | Select-Object -First 5 | ForEach-Object {
                    $subName = Split-Path $_.Path -Leaf
                    $subSize = Format-FileSize -Size $_.Size
                    Write-Host "        - $subName : $subSize" -ForegroundColor DarkCyan
                }
            }
            
            Write-Host ""
            $index++
        }
        
        Write-Host "  小计: " -NoNewline -ForegroundColor Gray
        Write-Host "$(Format-FileSize -Size $totalSafeSize)" -ForegroundColor Green
        Write-Host ""
    }
    
    # 显示谨慎清理项
    if ($cautiousItems.Count -gt 0) {
        Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Yellow
        Write-Host "  ! 【谨慎清理】 建议检查后删除" -ForegroundColor Yellow
        Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Yellow
        Write-Host "  这些目录可能包含配置或本地数据,删除前请确认`n" -ForegroundColor Gray
        
        $index = 1
        foreach ($item in $cautiousItems) {
            Write-Host "  [$index] $($item.Icon) $($item.Name)" -ForegroundColor White
            Write-Host "      大小: " -NoNewline -ForegroundColor Gray
            Write-Host "$($item.SizeFormatted)" -ForegroundColor Yellow
            Write-Host "      路径: " -NoNewline -ForegroundColor Gray
            Write-Host "$($item.Path)" -ForegroundColor Cyan
            Write-Host "      说明: $($item.Description)" -ForegroundColor DarkGray
            
            if ($item.Tips) {
                Write-Host "      ??  警告: $($item.Tips)" -ForegroundColor Yellow
            }
            
            Write-Host ""
            $index++
        }
        
        Write-Host "  小计: " -NoNewline -ForegroundColor Gray
        Write-Host "$(Format-FileSize -Size $totalCautiousSize)" -ForegroundColor Yellow
        Write-Host ""
    }
    
    # 总计
    Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Cyan
    Write-Host "  ?? 总计可清理空间: " -NoNewline -ForegroundColor White
    Write-Host "$(Format-FileSize -Size $totalSize)" -ForegroundColor Cyan
    Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`n" -ForegroundColor Cyan
    
    # 操作提示
    Write-Host "┌─────────────────────────────────────┐" -ForegroundColor White
    Write-Host "│  ?? 如何清理?                       │" -ForegroundColor White
    Write-Host "├─────────────────────────────────────┤" -ForegroundColor White
    Write-Host "│  1. 复制上面的路径                   │" -ForegroundColor Gray
    Write-Host "│  2. 在文件资源管理器中打开            │" -ForegroundColor Gray
    Write-Host "│  3. 确认内容后手动删除                │" -ForegroundColor Gray
    Write-Host "│  4. 某些文件可能提示占用,跳过即可     │" -ForegroundColor Gray
    Write-Host "└─────────────────────────────────────┘`n" -ForegroundColor White
    
    # 询问是否打开文件夹
    Write-Host "是否要打开某个文件夹查看?(输入序号,或按回车跳过): " -NoNewline -ForegroundColor Yellow
    $selection = Read-Host
    
    if ($selection -match '^\d+$') {
        $selectedIndex = [int]$selection - 1
        $allItems = $safeItems + $cautiousItems
        
        if ($selectedIndex -ge 0 -and $selectedIndex -lt $allItems.Count) {
            $selectedItem = $allItems[$selectedIndex]
            Write-Host "`n?? 正在打开: $($selectedItem.Path)" -ForegroundColor Green
            
            try {
                explorer.exe $selectedItem.Path
                Write-Host "? 已在文件资源管理器中打开`n" -ForegroundColor Green
            }
            catch {
                Write-Host "? 打开失败: $_`n" -ForegroundColor Red
            }
        }
        else {
            Write-Host "`n? 无效的序号`n" -ForegroundColor Red
        }
    }
}

# ============================================
# HTML 报告生成
# ============================================

function Export-HTMLReport {
    param(
        [array]$Results,
        [string]$OutputPath
    )
    
    $html = @"
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>C盘空间分析报告</title>
    <!-- Font Awesome 图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: 'Microsoft YaHei', 'Segoe UI', Arial, sans-serif; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .header h1 { font-size: 2.5em; margin-bottom: 10px; }
        .header h1 i { margin-right: 15px; }
        .header p { font-size: 1.1em; opacity: 0.9; }
        .summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            padding: 30px;
            background: #f8f9fa;
        }
        .summary-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
            transition: transform 0.3s;
        }
        .summary-card:hover {
            transform: translateY(-5px);
        }
        .summary-card .icon { 
            font-size: 2.5em; 
            margin-bottom: 10px; 
            color: #667eea;
        }
        .summary-card .icon.green { color: #28a745; }
        .summary-card .icon.orange { color: #fd7e14; }
        .summary-card .icon.blue { color: #17a2b8; }
        .summary-card .value { font-size: 2em; font-weight: bold; color: #333; }
        .summary-card .label { color: #666; margin-top: 5px; }
        .section {
            padding: 30px;
        }
        .section-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 3px solid #667eea;
        }
        .section-header.safe { border-color: #28a745; }
        .section-header.caution { border-color: #ffc107; }
        .section-header .icon { 
            font-size: 1.5em; 
            color: #667eea;
        }
        .section-header.safe .icon { color: #28a745; }
        .section-header.caution .icon { color: #ffc107; }
        .section-header h2 { font-size: 1.8em; color: #333; }
        .item {
            background: #f8f9fa;
            padding: 20px;
            margin-bottom: 15px;
            border-radius: 10px;
            border-left: 5px solid #667eea;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .item:hover {
            transform: translateX(5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .item.safe { border-left-color: #28a745; }
        .item.caution { border-left-color: #ffc107; }
        .item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .item-name {
            font-size: 1.3em;
            font-weight: bold;
            color: #333;
        }
        .item-name i {
            margin-right: 10px;
            color: #667eea;
        }
        .item.safe .item-name i { color: #28a745; }
        .item.caution .item-name i { color: #ffc107; }
        .item-size {
            font-size: 1.5em;
            font-weight: bold;
            color: #667eea;
        }
        .item-path {
            background: white;
            padding: 10px 15px;
            border-radius: 5px;
            font-family: 'Consolas', 'Courier New', monospace;
            font-size: 0.9em;
            color: #666;
            margin: 10px 0;
            word-break: break-all;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .item-path i {
            color: #667eea;
        }
        .item-desc {
            color: #666;
            margin: 10px 0;
            line-height: 1.6;
        }
        .item-tips {
            background: #fff3cd;
            border-left: 3px solid #ffc107;
            padding: 10px 15px;
            margin-top: 10px;
            border-radius: 5px;
            color: #856404;
            display: flex;
            align-items: flex-start;
            gap: 10px;
        }
        .item-tips i {
            margin-top: 3px;
        }
        .item-tips.warning {
            background: #f8d7da;
            border-left-color: #dc3545;
            color: #721c24;
        }
        .footer {
            background: #f8f9fa;
            padding: 30px;
            text-align: center;
            color: #666;
            border-top: 1px solid #dee2e6;
        }
        .footer .tips {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: left;
        }
        .footer .tips h3 {
            color: #667eea;
            margin-bottom: 15px;
            font-size: 1.3em;
        }
        .footer .tips h3 i {
            margin-right: 10px;
        }
        .footer .tips ol {
            margin-left: 20px;
            line-height: 2;
        }
        .footer .tips ol li {
            margin-bottom: 5px;
        }
        .badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 0.85em;
            font-weight: bold;
            margin-left: 10px;
        }
        .badge.safe { background: #d4edda; color: #155724; }
        .badge.caution { background: #fff3cd; color: #856404; }
        .no-print { }
        @media print {
            body { background: white; padding: 0; }
            .item:hover { transform: none; }
            .no-print { display: none; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-chart-pie"></i>C盘空间分析报告</h1>
            <p><i class="far fa-clock"></i> 生成时间:$(Get-Date -Format 'yyyy年MM月dd日 HH:mm:ss')</p>
        </div>
        
        <div class="summary">
            <div class="summary-card">
                <div class="icon blue"><i class="fas fa-search"></i></div>
                <div class="value">$($Results.Count)</div>
                <div class="label">发现项目</div>
            </div>
            <div class="summary-card">
                <div class="icon"><i class="fas fa-hdd"></i></div>
                <div class="value">$(Format-FileSize -Size (($Results | Measure-Object -Property Size -Sum).Sum))</div>
                <div class="label">可清理空间</div>
            </div>
            <div class="summary-card">
                <div class="icon green"><i class="fas fa-check-circle"></i></div>
                <div class="value">$(($Results | Where-Object { $_.SafeLevel -eq '安全' }).Count)</div>
                <div class="label">安全清理</div>
            </div>
            <div class="summary-card">
                <div class="icon orange"><i class="fas fa-exclamation-triangle"></i></div>
                <div class="value">$(($Results | Where-Object { $_.SafeLevel -eq '谨慎' }).Count)</div>
                <div class="label">谨慎清理</div>
            </div>
        </div>
"@

    # 安全清理项
    $safeItems = $Results | Where-Object { $_.SafeLevel -eq "安全" } | Sort-Object Size -Descending
    if ($safeItems.Count -gt 0) {
        $html += @"
        
        <div class="section">
            <div class="section-header safe">
                <span class="icon"><i class="fas fa-shield-alt"></i></span>
                <h2>安全清理项</h2>
                <span class="badge safe">可放心删除</span>
            </div>
"@
        
        foreach ($item in $safeItems) {
            # 根据项目类型选择图标
            $itemIcon = switch -Wildcard ($item.Name) {
                "*临时*"      { "fas fa-clock" }
                "*缓存*"      { "fas fa-database" }
                "*Cache*"     { "fas fa-database" }
                "*日志*"      { "fas fa-file-alt" }
                "*Log*"       { "fas fa-file-alt" }
                "*回收站*"    { "fas fa-trash-alt" }
                "*更新*"      { "fas fa-sync-alt" }
                "*安装*"      { "fas fa-download" }
                "*下载*"      { "fas fa-download" }
                "*备份*"      { "fas fa-copy" }
                "*报告*"      { "fas fa-file-medical-alt" }
                default       { "fas fa-folder" }
            }
            
            $html += @"
            <div class="item safe">
                <div class="item-header">
                    <div class="item-name"><i class="$itemIcon"></i>$($item.Name)</div>
                    <div class="item-size">$($item.SizeFormatted)</div>
                </div>
                <div class="item-path"><i class="fas fa-folder-open"></i><span>$($item.Path)</span></div>
                <div class="item-desc">$($item.Description)</div>
"@
            if ($item.Tips) {
                $html += @"
                <div class="item-tips"><i class="fas fa-lightbulb"></i><span>提示:$($item.Tips)</span></div>
"@
            }
            $html += @"
            </div>
"@
        }
        
        $html += @"
        </div>
"@
    }
    
    # 谨慎清理项
    $cautiousItems = $Results | Where-Object { $_.SafeLevel -eq "谨慎" } | Sort-Object Size -Descending
    if ($cautiousItems.Count -gt 0) {
        $html += @"
        
        <div class="section">
            <div class="section-header caution">
                <span class="icon"><i class="fas fa-exclamation-triangle"></i></span>
                <h2>谨慎清理项</h2>
                <span class="badge caution">建议检查后删除</span>
            </div>
"@
        
        foreach ($item in $cautiousItems) {
            # 根据项目类型选择图标
            $itemIcon = switch -Wildcard ($item.Name) {
                "*临时*"      { "fas fa-clock" }
                "*缓存*"      { "fas fa-database" }
                "*Cache*"     { "fas fa-database" }
                "*日志*"      { "fas fa-file-alt" }
                "*Log*"       { "fas fa-file-alt" }
                "*下载*"      { "fas fa-download" }
                "*备份*"      { "fas fa-copy" }
                "*应用*"      { "fas fa-th-large" }
                "*程序*"      { "fas fa-cog" }
                default       { "fas fa-folder" }
            }
            
            $html += @"
            <div class="item caution">
                <div class="item-header">
                    <div class="item-name"><i class="$itemIcon"></i>$($item.Name)</div>
                    <div class="item-size">$($item.SizeFormatted)</div>
                </div>
                <div class="item-path"><i class="fas fa-folder-open"></i><span>$($item.Path)</span></div>
                <div class="item-desc">$($item.Description)</div>
"@
            if ($item.Tips) {
                $html += @"
                <div class="item-tips warning"><i class="fas fa-exclamation-circle"></i><span>警告:$($item.Tips)</span></div>
"@
            }
            $html += @"
            </div>
"@
        }
        
        $html += @"
        </div>
"@
    }
    
    $html += @"
        
        <div class="footer">
            <div class="tips">
                <h3><i class="fas fa-book"></i>清理操作指南</h3>
                <ol>
                    <li><i class="fas fa-copy" style="color:#667eea;margin-right:5px;"></i>复制上面列出的路径</li>
                    <li><i class="fas fa-paste" style="color:#667eea;margin-right:5px;"></i>在文件资源管理器的地址栏中粘贴并打开</li>
                    <li><i class="fas fa-eye" style="color:#667eea;margin-right:5px;"></i>确认文件夹内容,确保不包含重要数据</li>
                    <li><i class="fas fa-trash-alt" style="color:#667eea;margin-right:5px;"></i>选中文件夹内容后按 <kbd>Shift</kbd>+<kbd>Delete</kbd> 彻底删除</li>
                    <li><i class="fas fa-redo" style="color:#667eea;margin-right:5px;"></i>如果提示文件被占用,可以跳过或稍后重试</li>
                    <li><i class="fas fa-shield-alt" style="color:#28a745;margin-right:5px;"></i>建议先清理"安全清理项",再考虑"谨慎清理项"</li>
                </ol>
            </div>
            <p><i class="fas fa-info-circle"></i> 本工具仅提供分析建议,删除操作需用户手动确认</p>
            <p style="margin-top: 10px; color: #999;">
                <i class="fas fa-tools"></i> C盘清理工具 v1.0 | 生成于 $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
            </p>
        </div>
    </div>
</body>
</html>
"@

    try {
        # 转换为绝对路径
        $absolutePath = if ([System.IO.Path]::IsPathRooted($OutputPath)) {
            $OutputPath
        } else {
            Join-Path (Get-Location) $OutputPath
        }
        
        # 使用 UTF-8 编码保存
        $utf8NoBom = New-Object System.Text.UTF8Encoding $false
        [System.IO.File]::WriteAllText($absolutePath, $html, $utf8NoBom)
        
        Write-Host ""
        Write-Host "  [OK] HTML报告已导出" -ForegroundColor Green
        Write-Host "       路径: $absolutePath" -ForegroundColor Gray
        
        # 验证并打开文件
        if (Test-Path $absolutePath) {
            Write-Host "       正在打开报告..." -ForegroundColor Gray
            Start-Process $absolutePath
        }
    }
    catch {
        Write-Host ""
        Write-Host "  [错误] 导出失败: $_" -ForegroundColor Red
    }
}

# ============================================
# 显示扫描结果(只显示,不处理交互)
# ============================================

function Show-ScanResults {
    param([array]$Results)
    
    if ($Results.Count -eq 0) {
        Write-Host "`n" -NoNewline
        Write-Host "  未发现可清理的项目,您的C盘很干净!" -ForegroundColor Green
        return
    }
    
    $totalSize = ($Results | Measure-Object -Property Size -Sum).Sum
    $safeItems = $Results | Where-Object { $_.SafeLevel -eq "安全" }
    $cautionItems = $Results | Where-Object { $_.SafeLevel -eq "谨慎" }
    
    Write-Host ""
    Write-Host "  ┌─────────────────────────────────────────────────────────┐" -ForegroundColor Cyan
    Write-Host "  │                    扫 描 结 果 汇 总                    │" -ForegroundColor Cyan
    Write-Host "  ├─────────────────────────────────────────────────────────┤" -ForegroundColor Cyan
    Write-Host "  │  " -NoNewline -ForegroundColor Cyan
    Write-Host "发现项目: " -NoNewline -ForegroundColor White
    Write-Host "$($Results.Count) 个".PadRight(15) -NoNewline -ForegroundColor Yellow
    Write-Host "可清理空间: " -NoNewline -ForegroundColor White
    Write-Host "$(Format-FileSize $totalSize)".PadRight(14) -NoNewline -ForegroundColor Green
    Write-Host "│" -ForegroundColor Cyan
    Write-Host "  │  " -NoNewline -ForegroundColor Cyan
    Write-Host "安全清理: " -NoNewline -ForegroundColor White
    Write-Host "$($safeItems.Count) 个".PadRight(15) -NoNewline -ForegroundColor Green
    Write-Host "谨慎清理: " -NoNewline -ForegroundColor White
    Write-Host "$($cautionItems.Count) 个".PadRight(16) -NoNewline -ForegroundColor Yellow
    Write-Host "│" -ForegroundColor Cyan
    Write-Host "  └─────────────────────────────────────────────────────────┘" -ForegroundColor Cyan
    
    # 显示详细列表
    Write-Host ""
    Write-Host "  ┌─────────────────────────────────────────────────────────┐" -ForegroundColor White
    Write-Host "  │  序号    大小        类型    名称                       │" -ForegroundColor White
    Write-Host "  ├─────────────────────────────────────────────────────────┤" -ForegroundColor White
    
    $sortedResults = $Results | Sort-Object Size -Descending
    $index = 1
    
    foreach ($item in $sortedResults) {
        $sizeStr = $item.SizeFormatted.PadRight(10)
        $levelColor = if ($item.SafeLevel -eq "安全") { "Green" } else { "Yellow" }
        $levelStr = "[$($item.SafeLevel)]".PadRight(8)
        $nameStr = if ($item.Name.Length -gt 28) { $item.Name.Substring(0, 25) + "..." } else { $item.Name.PadRight(28) }
        
        Write-Host "  │  " -NoNewline -ForegroundColor White
        Write-Host "$($index.ToString().PadLeft(2))    " -NoNewline -ForegroundColor Cyan
        Write-Host "$sizeStr" -NoNewline -ForegroundColor Green
        Write-Host "$levelStr" -NoNewline -ForegroundColor $levelColor
        Write-Host "$nameStr" -NoNewline -ForegroundColor White
        Write-Host " │" -ForegroundColor White
        
        $index++
    }
    
    Write-Host "  └─────────────────────────────────────────────────────────┘" -ForegroundColor White
}

# ============================================
# 交互式菜单
# ============================================

function Show-InteractiveMenu {
    param([array]$Results)
    
    $sortedResults = $Results | Sort-Object Size -Descending
    
    while ($true) {
        Write-Host ""
        Write-Host "  ┌─────────────────────────────────────────┐" -ForegroundColor Cyan
        Write-Host "  │              操 作 菜 单                │" -ForegroundColor Cyan
        Write-Host "  ├─────────────────────────────────────────┤" -ForegroundColor Cyan
        Write-Host "  │  " -NoNewline -ForegroundColor Cyan
        Write-Host "[序号]" -NoNewline -ForegroundColor Yellow
        Write-Host "  打开对应文件夹查看            │" -ForegroundColor White
        Write-Host "  │  " -NoNewline -ForegroundColor Cyan
        Write-Host "[R]" -NoNewline -ForegroundColor Yellow
        Write-Host "     重新显示扫描结果列表        │" -ForegroundColor White
        Write-Host "  │  " -NoNewline -ForegroundColor Cyan
        Write-Host "[H]" -NoNewline -ForegroundColor Yellow
        Write-Host "     重新打开HTML报告            │" -ForegroundColor White
        Write-Host "  │  " -NoNewline -ForegroundColor Cyan
        Write-Host "[C]" -NoNewline -ForegroundColor Yellow
        Write-Host "     打开Windows磁盘清理工具     │" -ForegroundColor White
        Write-Host "  │  " -NoNewline -ForegroundColor Cyan
        Write-Host "[Q]" -NoNewline -ForegroundColor Yellow
        Write-Host "     退出程序                    │" -ForegroundColor White
        Write-Host "  └─────────────────────────────────────────┘" -ForegroundColor Cyan
        Write-Host ""
        Write-Host "  请输入选项: " -NoNewline -ForegroundColor Yellow
        $choice = Read-Host
        
        # 退出
        if ($choice -eq 'Q' -or $choice -eq 'q' -or $choice -eq '0') {
            return "exit"
        }
        
        # 重新显示结果
        if ($choice -eq 'R' -or $choice -eq 'r') {
            Show-ScanResults -Results $Results
            continue
        }
        
        # 打开HTML报告
        if ($choice -eq 'H' -or $choice -eq 'h') {
            return "html"
        }
        
        # 打开磁盘清理工具
        if ($choice -eq 'C' -or $choice -eq 'c') {
            Write-Host ""
            Write-Host "  正在启动Windows磁盘清理工具..." -ForegroundColor Gray
            Start-Process "cleanmgr.exe" -ArgumentList "/d C"
            Write-Host "  [OK] 已启动磁盘清理工具" -ForegroundColor Green
            continue
        }
        
        # 数字序号 - 打开文件夹
        if ($choice -match '^\d+$') {
            $num = [int]$choice
            if ($num -ge 1 -and $num -le $sortedResults.Count) {
                $selectedItem = $sortedResults[$num - 1]
                $targetPath = $selectedItem.Path
                
                Write-Host ""
                Write-Host "  选择: $($selectedItem.Name)" -ForegroundColor Cyan
                Write-Host "  路径: $targetPath" -ForegroundColor Gray
                
                if (Test-Path $targetPath) {
                    Write-Host "  正在打开文件夹..." -ForegroundColor Gray
                    Start-Process "explorer.exe" -ArgumentList $targetPath
                    Write-Host "  [OK] 已在资源管理器中打开" -ForegroundColor Green
                    
                    # 显示该项的清理提示
                    if ($selectedItem.SafeLevel -eq "安全") {
                        Write-Host ""
                        Write-Host "  [提示] 这是安全清理项,可以放心删除文件夹内的内容" -ForegroundColor Green
                    } else {
                        Write-Host ""
                        Write-Host "  [警告] 这是谨慎清理项,请仔细检查后再删除!" -ForegroundColor Yellow
                    }
                    if ($selectedItem.Tips) {
                        Write-Host "  $($selectedItem.Tips)" -ForegroundColor Gray
                    }
                } else {
                    Write-Host "  [提示] 该路径不存在或已被清理" -ForegroundColor Yellow
                }
            } else {
                Write-Host ""
                Write-Host "  [错误] 无效序号,请输入 1-$($sortedResults.Count)" -ForegroundColor Red
            }
            continue
        }
        
        # 无效输入
        if (-not [string]::IsNullOrWhiteSpace($choice)) {
            Write-Host ""
            Write-Host "  [错误] 无效输入,请重新选择" -ForegroundColor Red
        }
    }
}

# ============================================
# 主程序入口
# ============================================

function Main {
    # 检查管理员权限
    $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    
    if (-not $isAdmin) {
        Write-Host ""
        Write-Host "  [提示] 未以管理员身份运行" -ForegroundColor Yellow
        Write-Host "         某些系统目录可能无法访问" -ForegroundColor Gray
        Write-Host "         建议右键选择「以管理员身份运行」" -ForegroundColor Gray
        Write-Host ""
        Write-Host "  是否继续?([Y] 继续 / [N] 退出): " -NoNewline -ForegroundColor Yellow
        $continue = Read-Host
        
        if ($continue -ne 'Y' -and $continue -ne 'y' -and $continue -ne '') {
            Write-Host ""
            Write-Host "  已取消操作" -ForegroundColor Cyan
            Write-Host ""
            return
        }
    }
    
    # 开始扫描
    $scanResults = Start-DiskScan
    
    if ($scanResults.Count -eq 0) {
        Write-Host ""
        Write-Host "  ========================================" -ForegroundColor Cyan
        Write-Host "       您的C盘很干净,未发现可清理项!" -ForegroundColor Green
        Write-Host "  ========================================" -ForegroundColor Cyan
        Write-Host ""
        return
    }
    
    # 显示扫描结果
    Show-ScanResults -Results $scanResults
    
    # 生成HTML报告路径
    $reportPath = Join-Path (Get-Location) "C盘清理报告_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"
    
    # 如果指定了导出路径,使用指定路径
    if ($ExportHTML) {
        $reportPath = $ExportHTML
    }
    
    # 自动生成HTML报告
    Write-Host ""
    Write-Host "  ----------------------------------------" -ForegroundColor Gray
    Write-Host "  正在生成HTML报告..." -ForegroundColor Cyan
    Export-HTMLReport -Results $scanResults -OutputPath $reportPath
    
    # 进入交互循环
    while ($true) {
        $action = Show-InteractiveMenu -Results $scanResults
        
        if ($action -eq "exit") {
            break
        }
        
        if ($action -eq "html") {
            if (Test-Path $reportPath) {
                Write-Host ""
                Write-Host "  正在打开HTML报告..." -ForegroundColor Gray
                Start-Process $reportPath
                Write-Host "  [OK] 已打开报告" -ForegroundColor Green
            } else {
                Write-Host ""
                Write-Host "  [提示] 报告文件不存在,正在重新生成..." -ForegroundColor Yellow
                Export-HTMLReport -Results $scanResults -OutputPath $reportPath
            }
        }
    }
    
    # 退出提示
    Write-Host ""
    Write-Host "  ========================================" -ForegroundColor Cyan
    Write-Host "        感谢使用 C盘清理工具!" -ForegroundColor Cyan
    Write-Host "  ========================================" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "  HTML报告已保存至:" -ForegroundColor Gray
    Write-Host "  $reportPath" -ForegroundColor White
    Write-Host ""
}

# 运行主程序
Main

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/sinat_41883985/article/details/156986823

文章来源转载

评论

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--