Loading

PowerShell实现定时备份并清理文件夹数据

脚本backup.ps1

# 设置执行策略以允许脚本运行
Set-ExecutionPolicy Bypass -Scope Process -Force

Write-Host "正在备份文件,请勿关闭...."

# 设置源目录和目标备份目录
# 备份源文件路径
$SOURCE_DIR = "D:\data\app\images"
# 备份目标路径
$BACKUP_DIR = "D:\data\backup"
$TIMESTAMP = (Get-Date).ToString('yyyyMMdd_HHmmss')
$BACKUP_FILE = "backup_$TIMESTAMP.zip"
# 备份日志文件
$LOG_FILE = "D:\data\backup\backup_$TIMESTAMP.log"

# 初始化标志变量
$FILES_FOUND = $false

# 创建临时目录用于存放备份文件
$TEMP_DIR = "$env:TEMP\backup_temp"
New-Item -ItemType Directory -Path $TEMP_DIR -Force | Out-Null

# 开始日志记录
Start-Transcript -Path $LOG_FILE -Append

Write-Host "Backup started at $(Get-Date)"
Write-Host "Source directory: $SOURCE_DIR"
Write-Host "Backup directory: $BACKUP_DIR"
Write-Host "Temporary directory: $TEMP_DIR"


# 查找并复制指定时间范围内的文件到临时目录(这边备份当前时间12小时之前得数据)
$startTime = (Get-Date).AddHours(-12)
$endTime = (Get-Date)


# 格式化时间以便输出
$formattedStartTime = $startTime.ToString("yyyy-MM-dd HH:mm:ss")
$formattedEndTime = $endTime.ToString("yyyy-MM-dd HH:mm:ss")

# 输出到控制台
Write-Host "Finding and copying files for $formattedStartTime to $formattedEndTime to a temporary directory"


Get-ChildItem -Path $SOURCE_DIR -Recurse | Where-Object {$_.CreationTime -ge $startTime -and $_.CreationTime -le $endTime} | ForEach-Object {
    # 获取文件或目录的相对路径
    $relativePath = $_.FullName.Substring($SOURCE_DIR.Length)

    # 构建目标路径
    $targetPath = Join-Path $TEMP_DIR $relativePath

    # 检查并创建目标路径,如果不存在
    if (-not (Test-Path $targetPath)) {
        New-Item -ItemType Directory -Path (Split-Path $targetPath -Parent) -Force | Out-Null
    }

    # 复制文件或目录
    Copy-Item $_.FullName -Destination $targetPath -Recurse -Force
    Write-Host "Copied: $_.FullName"
    $FILES_FOUND = $true
}

# 确保备份目录存在
if (-not (Test-Path $BACKUP_DIR)) {
    New-Item -ItemType Directory -Path $BACKUP_DIR | Out-Null
}

# 检查临时目录是否有文件,有文件则进行备份压缩
if ($FILES_FOUND) {
    Write-Host "Package and compress backup files..."
    Compress-Archive -Path "$TEMP_DIR\*" -DestinationPath "$BACKUP_DIR\$BACKUP_FILE" -Update
    if ($?) {
        Write-Host "Backup file created: $BACKUP_DIR\$BACKUP_FILE"
        Write-Host "Delete original files..."
        Get-ChildItem -Path $SOURCE_DIR -Recurse | Where-Object {$_.CreationTime -ge $startTime -and $_.CreationTime -le $endTime} | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
    } else {
        Write-Host "Error creating backup file"
    }
} else {
    Write-Host "The file does not exist and will not be backed up"
}

# 删除临时目录
Remove-Item -Path $TEMP_DIR -Recurse -Force

# 结束日志记录
if ($FILES_FOUND) {
	Write-Host "Backup completed at $(Get-Date)"
	Write-Host "Backup completed: $BACKUP_DIR\$BACKUP_FILE"
}
Stop-Transcript

windows定时执行

  1. 进入任务计划程序
  2. 新增定时任务
  3. 定时任务操作

    程序或脚本:%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
    添加参数:-File D:\backup.ps1
  4. 触发器不做介绍
posted @ 2024-06-01 14:56  IamHzc  阅读(147)  评论(0编辑  收藏  举报