You need to enable JavaScript to run this app. PowerShell 实现带排除项的文件夹内容删除需求咨询
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell 实现带排除项的文件夹内容删除需求咨询

PowerShell 目录自动清理脚本实现

可配置参数

以下参数可根据实际需求修改:

  • $parentDir:指定要清理的父目录路径
  • $deleteThresholdGB:删除总大小阈值,单位为GB,达到该值后脚本立即终止
  • $excludeRules:排除规则数组,支持通配符,匹配规则的文件不会被删除
  • $whatIfMode:测试模式开关,设为$true时仅打印待删除文件,不会实际执行删除,测试无误后改为$false

完整脚本

# -------------------------- 配置项开始 --------------------------
$parentDir = "C:\Test\ParentDirectory" # 替换为你的父目录路径
$deleteThresholdGB = 10 # 删满10GB就停止,可自行修改
$excludeRules = @(
    "*.exe", # 排除所有exe文件
    "*重要文件*", # 排除文件名含"重要文件"的文件
    "*\保留目录\*" # 排除路径含"保留目录"的文件
)
$whatIfMode = $true # 测试模式,改为$false才会实际删除
# -------------------------- 配置项结束 --------------------------

# 阈值转换为字节单位
$deleteThresholdBytes = $deleteThresholdGB * 1GB
$totalDeletedBytes = 0

# 1. 获取父目录下所有直接子文件夹
$directSubFolders = Get-ChildItem -Path $parentDir -Directory

# 2. 计算每个直接子文件夹下所有文件的最早上次访问时间,按时间升序排序
$sortedFolders = $directSubFolders | ForEach-Object {
    $folder = $_
    # 获取该文件夹下所有层级的文件
    $allFiles = Get-ChildItem -Path $folder.FullName -Recurse -File -ErrorAction SilentlyContinue
    $earliestAccessTime = if ($allFiles.Count -gt 0) {
        ($allFiles.LastAccessTime | Measure-Object -Minimum).Minimum
    } else {
        # 空文件夹默认排到最后
        Get-Date
    }
    [PSCustomObject]@{
        FolderPath = $folder.FullName
        EarliestAccessTime = $earliestAccessTime
    }
} | Sort-Object -Property EarliestAccessTime

# 3. 按排序结果遍历删除文件,统计删除大小
:outerLoop foreach ($folder in $sortedFolders) {
    # 获取当前文件夹下所有层级文件,排除匹配规则的文件
    $filesToDelete = Get-ChildItem -Path $folder.FolderPath -Recurse -File -ErrorAction SilentlyContinue | Where-Object {
        $file = $_
        $isExcluded = $false
        foreach ($rule in $excludeRules) {
            if ($file.FullName -like $rule) {
                $isExcluded = $true
                break
            }
        }
        -not $isExcluded
    }

    foreach ($file in $filesToDelete) {
        $fileSize = $file.Length
        # 执行删除
        if (-not $whatIfMode) {
            Remove-Item -Path $file.FullName -Force -ErrorAction SilentlyContinue
            # 仅删除成功的文件计入总大小
            if (-not $?) {
                continue
            }
        } else {
            Write-Host "待删除文件:$($file.FullName),大小:$([math]::Round($fileSize/1MB,2))MB"
        }

        # 累加已删除大小
        $totalDeletedBytes += $fileSize
        Write-Host "已删除总大小:$([math]::Round($totalDeletedBytes/1GB,2))GB / $deleteThresholdGB GB"

        # 4. 达到阈值立即终止所有循环
        if ($totalDeletedBytes -ge $deleteThresholdBytes) {
            Write-Host "已达到设定删除阈值,脚本终止运行"
            break outerLoop
        }
    }
}

Write-Host "脚本执行完成,累计删除大小:$([math]::Round($totalDeletedBytes/1GB,2))GB"

注意事项

首次使用请务必保持$whatIfMode = $true运行,确认待删除文件列表符合预期后再关闭测试模式执行实际删除,避免误删重要文件。


内容的提问来源于stack exchange,提问作者Carroll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 06:45:02