PowerShell调用DevOps API获取工作项时缺失Relations字段
问题分析与解决方案
核心问题排查
你遇到的问题根源在于New-WebRequest函数的几个实现缺陷,导致请求头不符合Azure DevOps API的预期,进而返回不完整的工作项数据:
- GET请求错误设置ContentType:GET请求没有请求体,设置
-ContentType属于冗余操作,可能干扰API对请求的解析,导致返回内容缺失关联关系字段。 - 未明确指定Accept请求头:浏览器默认会发送
Accept: application/json等头信息,而你的PowerShell请求未明确指定,API可能返回了非预期的响应格式。 - 字符串拼接命令的潜在风险:通过
[ScriptBlock]::Create拼接Invoke-WebRequest命令,容易出现参数解析错误(比如URL中的特殊字符处理),导致实际发送的请求与预期不符。
另外,Get-WorkItem函数中存在逻辑错误:判断Fields参数兼容性时,使用了-or而非-and,会导致错误触发参数不兼容的提示。
修正后的代码
修正版New-WebRequest函数
Function New-WebRequest { [CmdletBinding()] Param ( [ValidateNotNullOrEmpty()] [ValidateSet("GET", "POST")] [string] $Method = "GET", [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string] $ApiCall, [string] $RequestBody, [string] $RequestContentType = "application/json" ) if($ApiCall -notmatch $REGEX_URL) { Write-Error "The provided URL ($ApiCall) is not in the correct format" Exit 1 } try { Write-Debug "API Request Call: [$ApiCall]" # 构建参数哈希表,避免字符串拼接的解析问题 $requestParams = @{ Method = $Method Uri = $ApiCall UseBasicParsing = $true Headers = @{ Authorization = "Basic $ENCODED_PAT" Accept = "application/json" # 明确指定接受JSON格式 } } # 仅在POST请求且有请求体时,添加ContentType和Body参数 if ($Method -eq "POST" -and $PSBoundParameters.ContainsKey("RequestBody") -and -not([string]::IsNullOrWhiteSpace($RequestBody))) { Write-Debug "API Request Body: [$RequestBody]" $requestParams.ContentType = $RequestContentType $requestParams.Body = $RequestBody } $Response = Invoke-WebRequest @requestParams $StatusCode = $Response.StatusCode } catch { $StatusCode = $_.Exception.Response.StatusCode.value__ Write-Error "Error Occured: $_" } if ($StatusCode -eq 200) { $ResponseBody = $Response.Content | ConvertFrom-Json } else { throw "API Call failed (Status code: $StatusCode)" } return $ResponseBody }
修正版Get-WorkItem函数
Function Get-WorkItem { [CmdletBinding()] param ( [Parameter(Mandatory=$true, Position=0)] [ValidateNotNullOrEmpty()] [ValidatePattern("\d{5,6}")] [string] $Id, [ValidateSet("All", "None", "Fields", "Links", "Relations")] [string] $Expand = "All", [string[]] $Fields, [switch] $IncludeUpdates ) Write-Debug "Retrieving Work Item [$Id]..." $ApiCall = "$API_BASE_URL/wit/workitems/$($Id)?" $Params = @("`$expand=$Expand") if($PSBoundParameters.ContainsKey("Fields")) { # 修正逻辑判断:只有当Expand既不是None也不是Links时才报错 if($Expand -ne "None" -and $Expand -ne "Links" ) { Write-Error "The 'Fields' parameter can be used only if 'Expand' is 'None' or 'Links' as per API definition" } else { $Params += "fields=$($Fields -Join ",")" } } $ApiCall = Add-APIPart -URL $ApiCall -Params $Params $Body = New-WebRequest -ApiCall $ApiCall if($PSBoundParameters.ContainsKey("IncludeUpdates")) { $Call = "$API_BASE_URL/wit/workitems/$Id/updates" $Updates = (New-WebRequest -ApiCall $Call).Value } return if ($null -eq $Updates) { $Body } else { @{ Body = $Body; Updates = $Updates; } } }
验证步骤
- 运行修正后的代码,调用
Get-WorkItem -Id <工作项ID>(默认Expand=All),检查返回结果是否包含Relations字段。 - 若仍有问题,可在
New-WebRequest中添加Write-Debug $Response.Headers,对比浏览器请求头与PowerShell请求头的差异,进一步排查。
内容的提问来源于stack exchange,提问作者Fabrizio
相关产品推荐
相关产品推荐

