You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell实现Bitbucket备份校验与重试逻辑完善请求

Bitbucket备份脚本完善方案

需求与问题描述

执行java -jar命令完成Bitbucket备份后,需校验备份目录中是否存在今日创建/修改且大小不为0KB的文件:

  • 存在则提示备份成功,执行后续文件迁移操作
  • 不存在则重试备份1次,若仍失败则提示“备份未成功”

现有代码存在校验条件错误、重试逻辑缺失等问题,以下是完善后的方案:

完善后的PowerShell代码

# 定义Bitbucket备份与校验函数
function Invoke-BitbucketBackup {
    $backupClientPath = "C:\Atlassian\bitbucket-backup-client-4.0.0"
    $backupDir = Join-Path -Path $backupClientPath -ChildPath "backups"

    # 切换到备份客户端目录
    Set-Location -Path $backupClientPath
    Write-Host "已切换到目录: $backupClientPath" -ForegroundColor Cyan
    Write-Host "开始执行Bitbucket备份..." -ForegroundColor Cyan

    # 执行备份命令
    java -jar bitbucket-backup-client.jar

    # 校验有效备份文件:今日生成且大小>0KB
    $validBackupFiles = Get-ChildItem -Path $backupDir | Where-Object {
        $_.LastWriteTime.Date -eq (Get-Date).Date -and $_.Length -gt 0
    }

    # 返回校验结果:存在有效文件则返回$true
    return $null -ne $validBackupFiles -and $validBackupFiles.Count -gt 0
}

# 主执行逻辑:最多尝试2次备份(初始1次+重试1次)
$backupSuccess = $false
$retryCount = 0
$maxRetries = 1

while (-not $backupSuccess -and $retryCount -le $maxRetries) {
    if ($retryCount -gt 0) {
        Write-Host "第$($retryCount+1)次尝试备份..." -ForegroundColor Red
    }
    
    $backupSuccess = Invoke-BitbucketBackup

    if (-not $backupSuccess) {
        $retryCount++
        if ($retryCount -le $maxRetries) {
            Write-Host "备份失败,准备重试..." -ForegroundColor Red
        }
    }
}

# 最终结果处理
if ($backupSuccess) {
    Write-Host "Bitbucket备份成功!" -ForegroundColor Green
    Write-Host "======================================" -ForegroundColor Green
    # 此处添加后续文件迁移操作
    # 示例:Move-Item -Path "$backupDir\*" -Destination "D:\BackupStorage\Bitbucket"
} else {
    Write-Host "备份未成功" -ForegroundColor Red
    Write-Host "======================================" -ForegroundColor Red
}

关键修改说明

  1. 校验逻辑修复:
    • 新增文件大小判断$_.Length -gt 0,排除空文件
    • 修正变量引用错误,用$validBackupFiles替代未定义的$file_exists
  2. 备份逻辑封装:
    • 将备份、目录切换、校验逻辑封装为函数Invoke-BitbucketBackup,便于重复调用
  3. 重试机制实现:
    • 通过while循环控制最多执行2次备份,重试次数可通过$maxRetries调整
  4. 可读性优化:
    • 使用语义化变量名,添加清晰的状态提示,预留后续迁移操作的位置

内容的提问来源于stack exchange,提问作者ontljoshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 14:54:24