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

如何通过PowerShell脚本获取Git最新提交关联的Git Tag?

获取提交关联Git标签的PowerShell实现

当然可以通过PowerShell结合Azure DevOps REST API获取指定提交关联的Git标签,以下是在你现有脚本基础上的扩展实现:

完整脚本示例

# 原有获取分支最新Commit的代码
$uriBranchStatus = "https://dev.azure.com/$organization/$teamProject/_apis/git/repositories/$repoName/diffs/commits?baseVersion=$branchSourcePath&targetVersion=$branchTargetPath&api-version=6.0"
$resultStatus = Invoke-RestMethod -Uri $uriBranchStatus -Method Get -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
Write-Host "Latest commit in $branchSourcePath is $($resultStatus.baseCommit)"
Write-Host "Latest commit in $branchTargetPath is $($resultStatus.targetCommit)"

# 新增:根据Commit ID获取关联标签的函数
function Get-TagsByCommitId {
    param(
        [string]$organization,
        [string]$teamProject,
        [string]$repoName,
        [string]$commitId,
        [string]$base64AuthInfo
    )
    $uriTags = "https://dev.azure.com/$organization/$teamProject/_apis/git/repositories/$repoName/refs?filter=tags&objectId=$commitId&api-version=6.0"
    $tagResult = Invoke-RestMethod -Uri $uriTags -Method Get -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
    
    # 提取标签名称并处理无标签场景
    if ($tagResult.count -gt 0) {
        return $tagResult.value | ForEach-Object { $_.name -replace "^refs/tags/", "" }
    } else {
        return "无关联标签"
    }
}

# 获取并输出源分支提交的关联标签
$sourceTags = Get-TagsByCommitId -organization $organization -teamProject $teamProject -repoName $repoName -commitId $resultStatus.baseCommit -base64AuthInfo $base64AuthInfo
Write-Host "$branchSourcePath 最新提交关联的标签:$($sourceTags -join ', ')"

# 获取并输出目标分支提交的关联标签
$targetTags = Get-TagsByCommitId -organization $organization -teamProject $teamProject -repoName $repoName -commitId $resultStatus.targetCommit -base64AuthInfo $base64AuthInfo
Write-Host "$branchTargetPath 最新提交关联的标签:$($targetTags -join ', ')"

关键说明

  • 调用的Azure DevOps API会筛选出所有指向目标Commit ID的标签引用
  • 返回的标签名称默认带refs/tags/前缀,通过字符串替换提取纯标签名
  • 如果提交未关联任何标签,会返回“无关联标签”提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:22:48