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

如何在Azure DevOps中查询Package工作项的System.State状态?

解决Azure DevOps Package工作项System.State查询问题

原脚本存在的问题

  • WIQL查询仅选取了System.Id,未包含System.State字段
  • 函数参数$package与查询中使用的$PackageName名称不匹配
  • URL拆分逻辑错误(Split('')无实际作用)
  • Pipeline中调用的函数名checkPackagestate与脚本定义的TestState不一致

方案1:直接通过WIQL查询获取System.State

这种方式无需二次调用工作项详情接口,效率更高:

function TestState{
Param(
    [Parameter(Mandatory)]
    [string]
    $PackageName,  # 修正参数名与查询变量一致
    [Parameter(Mandatory)]
    [string]
    $secret,
    [Parameter(Mandatory)]
    [string]
    $DevopsProject
)
$header = prepareHeader $secret
# 修正WIQL,新增System.State字段查询
$query = "SELECT [System.Id], [System.State] FROM WorkItems WHERE [System.TeamProject] = '$DevopsProject' AND [System.WorkItemType] = 'Package' AND [System.Title] = '$PackageName' "
$json = @{ query = $query }
$jsonBody = ConvertTo-Json $json
$url  = "http://10.0.0.5/Test/$DevopsProject/_apis/wit/wiql?api-version=6.0"
$output = Invoke-RestMethod -Uri $url -Method Post -ContentType "application/json" -Headers $header -Body $jsonbody

# 提取并返回状态值,未找到则返回null
if ($output.workitems.Count -gt 0) {
    return $output.workitems.fields.'System.State'
} else {
    return $null
}
}

方案2:调用工作项详情接口获取System.State

如果需要获取更多工作项字段,可使用这种方式,同时修复URL处理逻辑:

function TestState{
Param(
    [Parameter(Mandatory)]
    [string]
    $PackageName,
    [Parameter(Mandatory)]
    [string]
    $secret,
    [Parameter(Mandatory)]
    [string]
    $DevopsProject
)
$header = prepareHeader $secret
$query = "SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = '$DevopsProject' AND [System.WorkItemType] = 'Package' AND [System.Title] = '$PackageName' "
$json = @{ query = $query }
$jsonBody = ConvertTo-Json $json
$url  = "http://10.0.0.5/Test/$DevopsProject/_apis/wit/wiql?api-version=6.0"
$output = Invoke-RestMethod -Uri $url -Method Post -ContentType "application/json" -Headers $header -Body $jsonbody

if ($output.workitems.Count -gt 0) {
    # 直接使用工作项URL,指定仅获取System.State字段减少数据传输
    $workItemUrl = $output.workitems.url + "&fields=System.State"
    $workItem = Invoke-RestMethod -Uri $workItemUrl -Method Get -ContentType "application/json" -Headers $header
    return $workItem.fields.'System.State'
} else {
    return $null
}
}

修正Pipeline配置

确保函数名和参数传递格式正确:

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
        # 匹配脚本定义的函数名,修正参数引号与格式
        $test = TestState -PackageName "$PackageName" -secret "$(secret)" -DevopsProject "$(DevopsProject)"
        # 输出查询到的状态
        Write-Host "Package工作项状态:$test"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:25:17