批量删除空文件夹的脚本

wen 实用脚本 2

本文目录导读:

批量删除空文件夹的脚本

  1. Windows (批处理 .bat)
  2. Windows (PowerShell)
  3. Linux/macOS (Bash)
  4. Python 版本 (跨平台)
  5. 使用说明

Windows (批处理 .bat)

@echo off
chcp 65001 >nul批量删除空文件夹工具
color 0A
echo ========================================
echo        批量删除空文件夹工具
echo ========================================
echo.
set /p target=请输入要清理的目录路径: 
if not exist "%target%" (
    echo 错误:路径不存在!
    pause
    exit /b
)
echo.
echo 正在扫描空文件夹...
echo.
set count=0
for /f "delims=" %%i in ('dir "%target%" /s /b /ad ^| sort /r') do (
    if exist "%%i" (
        dir /a /b "%%i" 2>nul | findstr /r "." >nul
        if errorlevel 1 (
            echo 删除空文件夹: %%i
            rmdir "%%i" 2>nul
            if not errorlevel 1 (
                set /a count+=1
            )
        )
    )
)
echo.
echo ========================================
echo 清理完成!共删除 %count% 个空文件夹
echo ========================================
pause

Windows (PowerShell)

# 批量删除空文件夹 PowerShell脚本
Write-Host "========================================" -ForegroundColor Green
Write-Host "        批量删除空文件夹工具" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
$targetPath = Read-Host "请输入要清理的目录路径"
if (-not (Test-Path $targetPath)) {
    Write-Host "错误:路径不存在!" -ForegroundColor Red
    pause
    exit
}
Write-Host ""
Write-Host "正在扫描空文件夹..." -ForegroundColor Yellow
$count = 0
# 递归查找所有文件夹,按深度排序
$folders = Get-ChildItem -Path $targetPath -Directory -Recurse | 
           Sort-Object { $_.FullName.Split('\').Count } -Descending
foreach ($folder in $folders) {
    $isEmpty = (Get-ChildItem -Path $folder.FullName -Force | Measure-Object).Count -eq 0
    if ($isEmpty) {
        Write-Host "删除空文件夹: $($folder.FullName)" -ForegroundColor Cyan
        Remove-Item -Path $folder.FullName -Force
        $count++
    }
}
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "清理完成!共删除 $count 个空文件夹" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Read-Host "按回车键退出"

Linux/macOS (Bash)

#!/bin/bash
# 批量删除空文件夹脚本
clear
echo "========================================"
echo "        批量删除空文件夹工具"
echo "========================================"
echo ""
# 获取目标路径
read -p "请输入要清理的目录路径: " target_path
# 检查路径是否存在
if [ ! -d "$target_path" ]; then
    echo "错误:路径不存在!"
    exit 1
fi
echo ""
echo "正在扫描空文件夹..."
echo ""
# 统计删除数量
count=0
# 查找并删除空文件夹(从最深层开始)
while IFS= read -r folder; do
    # 检查文件夹是否为空
    if [ -d "$folder" ] && [ -z "$(ls -A "$folder" 2>/dev/null)" ]; then
        echo "删除空文件夹: $folder"
        rmdir "$folder" 2>/dev/null
        if [ $? -eq 0 ]; then
            ((count++))
        fi
    fi
done < <(find "$target_path" -type d -depth)
echo ""
echo "========================================"
echo "清理完成!共删除 $count 个空文件夹"
echo "========================================"
echo ""
read -p "按回车键退出"

Python 版本 (跨平台)

import os
import sys
from pathlib import Path
def delete_empty_folders(root_path, dry_run=False):
    """
    递归删除空文件夹
    """
    deleted_count = 0
    # 从最深层级开始遍历
    for dirpath, dirnames, filenames in os.walk(root_path, topdown=False):
        # 跳过根目录本身
        if os.path.abspath(dirpath) == os.path.abspath(root_path):
            continue
        # 检查是否为空文件夹
        if not dirnames and not filenames:
            try:
                if dry_run:
                    print(f"[预览] 将删除: {dirpath}")
                else:
                    print(f"删除空文件夹: {dirpath}")
                    os.rmdir(dirpath)
                deleted_count += 1
            except OSError as e:
                print(f"删除失败 {dirpath}: {e}")
    return deleted_count
def main():
    print("========================================")
    print("        批量删除空文件夹工具")
    print("========================================")
    print()
    # 获取目标路径
    root_path = input("请输入要清理的目录路径: ").strip()
    # 检查路径
    if not os.path.exists(root_path):
        print("错误:路径不存在!")
        sys.exit(1)
    # 预览模式
    preview = input("是否预览模式?(y/n): ").lower() == 'y'
    print()
    print("正在扫描空文件夹...")
    print()
    deleted = delete_empty_folders(root_path, dry_run=preview)
    print()
    print("========================================")
    mode = "预览" if preview else "清理"
    print(f"{mode}完成!共处理 {deleted} 个空文件夹")
    print("========================================")
    input("\n按回车键退出")
if __name__ == "__main__":
    main()

使用说明

  1. 选择适合您的版本

    • Windows用户:使用 .bat 或 PowerShell 版本
    • Linux/macOS用户:使用 Bash 版本
    • 需要跨平台:使用 Python 版本
  2. 安全提示

    • 建议先在一个测试目录中试运行
    • 部分版本提供"预览模式",先查看将删除哪些文件夹
    • 删除操作不可恢复,请谨慎使用
  3. 使用步骤

    • 保存脚本为对应格式文件(如 .bat.sh.ps1.py
    • Linux/macOS需要先添加执行权限:chmod +x 脚本名称.sh
    • Windows 可能需要以管理员身份运行
  4. 注意事项

    • 脚本只删除空文件夹,不会删除有内容的文件夹
    • 会从最深层开始删除,确保正确处理嵌套结构
    • 某些受保护的系统文件夹可能无法删除

您可以根据需要选择合适的版本使用。

抱歉,评论功能暂时关闭!