本文目录导读:

我来介绍几种常见的自动化清理系统垃圾脚本方案,适用于不同操作系统。
Windows 系统清理脚本
批处理脚本 (clean.bat)
@echo off系统垃圾清理工具 echo 正在清理系统垃圾文件... :: 清理临时文件 del /f /s /q %systemdrive%\*.tmp del /f /s /q %systemdrive%\*._mp del /f /s /q %systemdrive%\*.log del /f /s /q %systemdrive%\*.gid del /f /s /q %systemdrive%\*.chk del /f /s /q %systemdrive%\*.old del /f /s /q %windir%\*.bak :: 清理回收站 rd /s /q %systemdrive%\$Recycle.Bin :: 清理预读取文件 del /f /s /q %windir%\Prefetch\* :: 清理临时文件夹 rd /s /q %temp% rd /s /q %windir%\temp md %temp% md %windir%\temp :: 清理浏览器缓存(Chrome) rd /s /q "%localappdata%\Google\Chrome\User Data\Default\Cache\*" echo 清理完成! pause
PowerShell 脚本 (clean.ps1)
Write-Host "系统垃圾清理开始..." -ForegroundColor Green
# 清理临时文件
$tempFolders = @(
"$env:TEMP",
"$env:WINDIR\Temp",
"$env:WINDIR\Prefetch"
)
foreach ($folder in $tempFolders) {
if (Test-Path $folder) {
Remove-Item "$folder\*" -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "已清理: $folder" -ForegroundColor Yellow
}
}
# 清理回收站
Clear-RecycleBin -Force -ErrorAction SilentlyContinue
# 清理 Windows 更新缓存
Dism /Online /Cleanup-Image /StartComponentCleanup /ResetBase
# 清理系统文件卫士的备份
Dism /Online /Cleanup-Image /SPSuperseded
Write-Host "清理完成!" -ForegroundColor Green
Linux 系统清理脚本
Bash 脚本 (clean.sh)
#!/bin/bash
echo "开始清理系统垃圾..."
# 清理 apt 缓存
sudo apt-get clean
sudo apt-get autoremove -y
sudo apt-get autoclean
# 清理临时文件
sudo rm -rf /tmp/*
sudo rm -rf /var/tmp/*
# 清理日志文件
sudo journalctl --vacuum-time=7d
# 清理包缓存
sudo rm -rf ~/.cache/*
# 清理旧的 snap 版本
sudo snap list --all | awk '/disabled/{print $1, $3}' |
while read snapname revision; do
sudo snap remove "$snapname" --revision="$revision"
done
# 清理 Docker 未使用的资源(如果安装)
if command -v docker &> /dev/null; then
docker system prune -f
fi
echo "清理完成!"
设置定时任务
# 创建定时清理任务(每天凌晨2点执行) sudo crontab -e # 添加以下行 0 2 * * * /path/to/clean.sh >> /var/log/clean.log 2>&1
macOS 系统清理脚本
Shell 脚本 (clean_mac.sh)
#!/bin/bash
echo "开始清理 macOS 系统垃圾..."
# 清理系统日志
sudo rm -rf /private/var/log/*
sudo rm -rf /Library/Logs/*
# 清理用户缓存
rm -rf ~/Library/Caches/*
rm -rf ~/Library/Logs/*
# 清理临时文件
sudo rm -rf /private/var/tmp/*
sudo rm -rf /private/tmp/*
# 清理下载文件夹中的旧文件(30天前)
find ~/Downloads -type f -mtime +30 -delete
# 清理 Xcode 衍生产品(如果安装)
rm -rf ~/Library/Developer/Xcode/DerivedData/*
# 清理 Docker 未使用的资源(如果安装)
if command -v docker &> /dev/null; then
docker system prune -f
fi
echo "清理完成!"
跨平台 Python 脚本
Python 脚本 (clean.py)
#!/usr/bin/env python3
import os
import sys
import shutil
import platform
def clean_temp_files():
"""清理临时文件"""
temp_dirs = []
if platform.system() == "Windows":
temp_dirs = [
os.environ.get('TEMP', ''),
os.environ.get('TMP', ''),
os.path.join(os.environ.get('WINDIR', ''), 'Temp')
]
elif platform.system() == "Linux":
temp_dirs = ['/tmp', '/var/tmp']
elif platform.system() == "Darwin": # macOS
temp_dirs = ['/tmp', '/var/tmp']
for temp_dir in temp_dirs:
if os.path.exists(temp_dir):
try:
for item in os.listdir(temp_dir):
item_path = os.path.join(temp_dir, item)
if os.path.isfile(item_path):
os.remove(item_path)
elif os.path.isdir(item_path):
shutil.rmtree(item_path)
print(f"已清理: {temp_dir}")
except Exception as e:
print(f"清理 {temp_dir} 时出错: {e}")
def clean_recycle_bin():
"""清理回收站(仅Windows)"""
if platform.system() == "Windows":
import subprocess
subprocess.run(['cmd', '/c', 'rd /s /q C:\\$Recycle.Bin'],
capture_output=True)
def clean_browser_cache():
"""清理浏览器缓存"""
home = os.path.expanduser("~")
# Chrome
chrome_cache = [
os.path.join(home, "Library/Caches/Google/Chrome") if platform.system() == "Darwin" else "",
os.path.join(home, ".cache/google-chrome") if platform.system() == "Linux" else "",
os.path.join(os.environ.get('LOCALAPPDATA', ''), "Google/Chrome/User Data/Default/Cache") if platform.system() == "Windows" else ""
]
for cache_path in chrome_cache:
if cache_path and os.path.exists(cache_path):
try:
shutil.rmtree(cache_path)
print(f"已清理 Chrome 缓存: {cache_path}")
except Exception as e:
print(f"清理 Chrome 缓存时出错: {e}")
if __name__ == "__main__":
print("系统垃圾清理工具")
print("=" * 30)
clean_temp_files()
clean_recycle_bin()
clean_browser_cache()
print("清理完成!")
安全注意事项
- 备份重要数据:运行清理脚本前确保重要数据已备份
- 测试运行:先在测试环境运行脚本
- 权限控制:使用管理员权限运行关键清理操作
- 定期维护:建议每周运行一次清理脚本
- 选择性清理:根据实际需求调整清理范围
监控清理效果
# PowerShell 监控磁盘空间
$drives = Get-PSDrive -PSProvider FileSystem
foreach ($drive in $drives) {
$percent = [math]::Round(($drive.Used / $drive.Free) * 100, 2)
Write-Host "驱动器 $($drive.Name): 已用 $percent%"
}
选择适合你系统的脚本,并根据需要调整清理范围,建议先手动测试,确认无误后再设置自动执行。