Azure DevOps Server Maintain

2025-10-07

說明如何分析 Azure DevOps Server 各專案的儲存空間使用情況,並整理不必要的資料以釋放空間。

logo

說明

首先觀察每天個別 Collection 所產生的 bak 檔案大小。

透過以下 PowerShell 列出 Collection 下各專案以及 Repo 所使用的儲存空間,需要使用:

$server = "FQDN"
$collection = "DefaultCollection"

$projectsApi = "http://$server/$collection/_apis/projects?api-version=6.0"
$projects = (Invoke-RestMethod -Uri $projectsApi -UseDefaultCredentials).value

$gitResults = @()
foreach ($project in $projects) {
    $projectName = $project.name
    Write-Host "處理專案: $projectName"
    
    try {
    $reposApi = "http://$server/$collection/$projectName/_apis/git/repositories?api-version=6.0"
    $repos = (Invoke-RestMethod -Uri $reposApi -UseDefaultCredentials).value
        
        $projectTotal = 0
        foreach ($repo in $repos) {
            $sizeInMB = [math]::Round(($repo.size / 1MB), 2)
            $projectTotal += $sizeInMB
            
            $gitResults += [PSCustomObject]@{
                Project = $projectName
                Repository = $repo.name
                SizeInMB = $sizeInMB
            }
        }
        
        Write-Host "  專案總容量: $projectTotal MB"
    }
    catch {
        Write-Host "  無法取得 Git repositories: $_" -ForegroundColor Yellow
    }
}

# 依專案統計
Write-Host "`n=== 各專案 Git 容量統計 ===" -ForegroundColor Green
$gitResults | Group-Object Project | 
    Select-Object Name, 
        @{N='RepoCount';E={$_.Count}},
        @{N='TotalMB';E={[math]::Round(($_.Group | Measure-Object SizeInMB -Sum).Sum, 2)}} | 
    Sort-Object TotalMB -Descending |
    Format-Table -AutoSize

# 列出最大的 repositories
Write-Host "`n=== 最大的 20 個 Repositories ===" -ForegroundColor Green
$gitResults | Sort-Object SizeInMB -Descending | 
    Select-Object -First 20 |
    Format-Table -AutoSize

# 匯出結果
$gitResults | Export-Csv -Path "C:\Temp\GitRepoSizes.csv" -NoTypeInformation -Encoding UTF8
Write-Host "`n結果已匯出至 C:\Temp\GitRepoSizes.csv" -ForegroundColor Cyan

如果是 Repos 佔據太多空間,可以透過整理 Commits 來減少空間使用

處理完成之後,需要在 Collection 資料庫中執行以下查詢, 來釋放資料庫空間:

SELECT 
    name AS FileName,
    size/128.0 AS CurrentSizeMB,
    size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS INT)/128.0 AS FreeSpaceMB
FROM sys.database_files

EXEC prc_CleanupDeletedFileContentSegmentedBatchSelect 1,0,0,1,0
GO 1

EXEC prc_DeleteUnusedFiles 1, 0, 100000
GO