用脚本删除过期文件怎么做

wen 实用脚本 1

本文目录导读:

用脚本删除过期文件怎么做

  1. Linux/Unix Shell 脚本
  2. Windows 批处理脚本
  3. PowerShell 脚本
  4. Python 脚本(跨平台)
  5. 定时执行方案
  6. 使用建议

Linux/Unix Shell 脚本

使用 find 命令(最常用)

#!/bin/bash
# 删除30天前的文件
find /path/to/files -type f -mtime +30 -delete
# 更安全的版本(先列出再删除)
find /path/to/files -type f -mtime +30 -exec rm {} \;
# 按分钟删除(例如删除10分钟前的文件)
find /path/to/files -type f -mmin +10 -delete
# 按小时删除
find /path/to/files -type f -mtime +2 -name "*.log" -delete

带日志记录和错误处理的完整脚本

#!/bin/bash
# 删除过期日志文件
LOG_DIR="/var/log/myapp"
DAYS=30
LOG_FILE="/var/log/cleanup.log"
# 检查目录是否存在
if [ ! -d "$LOG_DIR" ]; then
    echo "[$(date)] 目录不存在: $LOG_DIR" >> $LOG_FILE
    exit 1
fi
# 统计删除的文件
DELETED_COUNT=0
echo "[$(date)] 开始清理 $LOG_DIR 中 $DAYS 天前的文件" >> $LOG_FILE
# 查找并删除文件
while IFS= read -r file; do
    rm "$file"
    DELETED_COUNT=$((DELETED_COUNT + 1))
    echo "[$(date)] 已删除: $file" >> $LOG_FILE
done < <(find $LOG_DIR -type f -mtime +$DAYS)
echo "[$(date)] 清理完成,共删除 $DELETED_COUNT 个文件" >> $LOG_FILE

Windows 批处理脚本

@echo off
REM 删除30天前的文件
forfiles /p "C:\logs" /s /m *.log /d -30 /c "cmd /c del @path"
REM 删除指定类型的文件
forfiles /p "C:\temp" /d -7 /c "cmd /c del @file"
REM 递归删除子目录中的过期文件
forfiles /p "C:\backup" /s /d -90 /c "cmd /c del @path"

PowerShell 脚本

# 删除30天前的文件
$threshold = (Get-Date).AddDays(-30)
Get-ChildItem -Path "C:\logs" -Recurse | 
    Where-Object { $_.LastWriteTime -lt $threshold -and !$_.PSIsContainer } |
    Remove-Item -Force
# 带日志的版本
$logFile = "C:\cleanup.log"
$deletedCount = 0
Get-ChildItem -Path "C:\logs" -File | 
    Where-Object { $_.LastWriteTime -lt $threshold } | 
    ForEach-Object {
        Remove-Item $_.FullName -Force
        $deletedCount++
        Add-Content $logFile "$(Get-Date) - 已删除: $($_.FullName)"
    }
Add-Content $logFile "$(Get-Date) - 共删除 $deletedCount 个文件"

Python 脚本(跨平台)

import os
import time
from pathlib import Path
import logging
# 配置日志
logging.basicConfig(filename='cleanup.log', level=logging.INFO)
def delete_old_files(directory, days, extensions=None):
    """
    删除指定目录下超过指定天数的文件
    Args:
        directory: 目标目录
        days: 过期天数
        extensions: 文件扩展名列表(可选)
    """
    cutoff_time = time.time() - days * 86400
    deleted_count = 0
    try:
        for root, dirs, files in os.walk(directory):
            for filename in files:
                # 检查扩展名
                if extensions and not any(filename.endswith(ext) for ext in extensions):
                    continue
                file_path = os.path.join(root, filename)
                try:
                    file_mtime = os.path.getmtime(file_path)
                    if file_mtime < cutoff_time:
                        os.remove(file_path)
                        deleted_count += 1
                        logging.info(f"已删除: {file_path}")
                except OSError as e:
                    logging.error(f"删除失败 {file_path}: {e}")
    except Exception as e:
        logging.error(f"遍历目录错误: {e}")
    logging.info(f"共删除 {deleted_count} 个文件")
    return deleted_count
# 使用示例
if __name__ == "__main__":
    # 删除30天前的日志文件
    delete_old_files("/var/log/app", 30, ['.log'])
    # 删除所有类型的过期文件
    # delete_old_files("/tmp/old", 7)

定时执行方案

Linux crontab

# 每天凌晨2点执行清理
0 2 * * * /usr/local/bin/cleanup.sh
# 每周日执行
0 2 * * 0 /usr/local/bin/cleanup.sh

Windows 计划任务

# 创建计划任务
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "C:\scripts\cleanup.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "02:00"
Register-ScheduledTask -TaskName "CleanupOldFiles" -Action $action -Trigger $trigger

使用建议

  1. 先测试:正式运行前先用 -whatif 或打印模式测试
  2. 备份重要:对重要目录建议先备份
  3. 日志记录:保留操作日志便于追踪
  4. 权限管理:确保脚本有适当的执行权限
  5. 安全网:可以先将文件移动到回收站/备份目录而不是直接删除

选择哪种脚本取决于你的操作系统和具体需求,建议先用 echo-whatif 参数测试,确认无误后再正式执行。

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