使用Rest API排队带变量构建失败,报错TF400898
UNC路径触发Azure DevOps Rest API内部错误的原因与解决方法
问题原因
- JSON转义规则要求:JSON格式中,字符串里的反斜杠
\必须转义为\\才能被正确解析。 - 手动拼接JSON的转义遗漏:你直接将PowerShell中的UNC路径字符串拼接到
parameters的JSON片段中,PowerShell双引号字符串会把\\解析为单个\,导致最终生成的JSON片段中反斜杠未正确转义,不符合API的格式要求,触发内部错误。 - 双重序列化的叠加影响:代码先手动拼接了
parameters的JSON字符串,再将整个$body哈希表通过ConvertTo-Json序列化,进一步加剧了转义错误的问题。
解决方法
方法1:用嵌套哈希表统一处理序列化(推荐)
避免手动拼接JSON,通过嵌套哈希表让PowerShell自动处理转义逻辑,确保最终发送的JSON格式完全符合API要求:
$BuildPath = "\\xxx.com\global\Engineering\Builds\Agile" $BranchName = "v8.6.4x-SP" $releaseUri = "https://dev.azure.com/xxx/Idu%20Client-Server/_apis/build/builds?api-version=5.0-preview" $body = @{ definition = @{ id = "26845" } # 先将参数序列化为JSON字符串,作为parameters字段的值 parameters = @{ BranchName = $BranchName BuildPath = $BuildPath } | ConvertTo-Json -Compress } $releaseResponse = Invoke-RestMethod -Method Post -ContentType "application/json" -Uri $releaseUri -Body ($body | ConvertTo-Json -Compress -Depth 10) -Headers $header
方法2:手动转义UNC路径中的反斜杠
如果需要保留手动拼接的方式,需将路径中的每个\替换为\\\\(适配JSON的双重转义要求):
$BuildPath = "\\xxx.com\global\Engineering\Builds\Agile" # 转义路径中的反斜杠,适配JSON格式 $escapedBuildPath = $BuildPath -replace "\\", "\\\\" $BranchName = "v8.6.4x-SP" $releaseUri = "https://dev.azure.com/xxx/Idu%20Client-Server/_apis/build/builds?api-version=5.0-preview" $body = @{ definition = @{ id = "26845" } parameters = '{"BranchName":"' + $BranchName + '","BuildPath":"' + $escapedBuildPath + '"}' } $releaseResponse = Invoke-RestMethod -Method Post -ContentType "application/json" -Uri $releaseUri -Body ($body | ConvertTo-Json -Compress -Depth 10) -Headers $header
内容的提问来源于stack exchange,提问作者Bandit
相关产品推荐
相关产品推荐

