powershell脚本定期清理旧的备份文件,定期转移备份文件
powershell脚本定期清理旧的备份文件
场景说明:
运维部门部署了一台独立的备份服务器,通过dblink远程备份数据库schema数据,久而久之,备份文件越来越多,导致磁盘空间不足。
先计划使用powsershell脚本定期清理6个月之前的备份文件。
测试脚本如下,将以下脚本内容保存为.ps1后缀的文件即可:
# 定义清理参数
$targetPath = "D:\tempfile"
$logfiledir = "D:\scripts\logs"
$daysThreshold = 180
$cutoffDate = (Get-Date).AddDays(-$daysThreshold)
$logPath = Join-Path $logfiledir "Cleanup_olddumpfile_$(Get-Date -Format 'yyyyMMdd').log"# 获取符合条件的文件
$filesToDelete = Get-ChildItem -Path $targetPath -Recurse -File |Where-Object { $_.LastWriteTime -lt $cutoffDate }# 记录操作信息
"清理任务启动时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" | Out-File $logPath -Append
"文件保留阈值: $daysThreshold 天" | Out-File $logPath -Append
"清理截止日期: $($cutoffDate.ToString('yyyy-MM-dd'))" | Out-File $logPath -Append
"发现符合条件的文件: $($filesToDelete.Count) 个" | Out-File $logPath -Append# 执行清理操作
if ($filesToDelete.Count -gt 0) {foreach ($file in $filesToDelete) {try {$file | Remove-Item -Force -ErrorAction Stop"[成功] 已删除:$($file.FullName)" | Out-File $logPath -Append}catch {"[错误] 删除失败:$($file.FullName) - $_" | Out-File $logPath -Append}}
}"清理任务完成时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" | Out-File $logPath -Append
"--------------------------------------------------" | Out-File $logPath -Append
脚本编写好之后,配合windows定时任务即可实现自动清理,powershell脚本的定时任务写法与bat方式有些差别,不能直接指定ps文件路径。
另外在之前的场景中,同在这个备份服务器中,D盘的空间用于存放当前最新的7天的备份文件,超过7天前的文件使用powershell脚本转移到E盘中。
脚本如下:
# 定义源目录和目标目录
$sourceDir = "D:\DMP\"
$targetDir = "E:\DMP"
$logFile = "D:\scripts\logs\move_file.log"# 获取当前时间并计算7天前的时间
$sevenDaysAgo = (Get-Date).AddDays(-3)# 获取源目录下所有7天前的.tar.gz文件
$dmpFiles = Get-ChildItem -Path $sourceDir -Filter *.tar.gz | Where-Object { $_.LastWriteTime -le $sevenDaysAgo }# 如果没有符合条件的文件,则退出脚本
if ($dmpFiles.Count -eq 0) {Write-Output "没有找到7天前的.tar.gz文件,无需转移!"Exit
}# 计算所有符合条件的.tar.gz文件的总大小(字节)
$totalSize = ($dmpFiles | Measure-Object -Property Length -Sum).Sum# 获取目标磁盘 E: 的可用空间(字节)
$eDrive = Get-PSDrive E
$availableSpace = $eDrive.Free# 检查可用空间是否足够
if ($totalSize -gt $availableSpace) {# 如果空间不足,弹出提示并退出Write-Output "不满足转移:E盘剩余空间不足!"Exit
}# 如果空间足够,开始移动文件
foreach ($file in $dmpFiles) {Move-Item -Path $file.FullName -Destination $targetDir -Force# 将已转移的文件名记录到日志文件Add-Content -Path $logFile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Moved: $($file.Name)"
}# 移动完成后提示
Write-Output "转移完成!已转移的文件已记录到日志文件:$logFile"