更新/创建TFS服务器变量组使用REST API与powershell给出对象引用未设置



好吧,我已经摆弄这个几个小时了,我似乎找不到任何在线资源或解决这个问题。

查看api文档https://learn.microsoft.com/en-us/rest/api/azure/devops/distributedtask/variablegroups/get?view=azure-devops-rest-6.0

我可以得到关于我作为测试创建的变量组的信息:

$invRestMethParams = @{
Uri = "https://xxx.xxx.nl/tfs/DefaultCollection/$($project)/_apis/distributedtask/variablegroups/242/?api-version=6.0-preview.2"
Method = 'GET'
ContentType = 'application/json'
}
Invoke-RestMethod @invRestMethParams -UseDefaultCredentials

然后将结果转换为json以获得PUT或POST更新或创建所需的值:

{
"variables":  {
"check":  {
"value":  "value"
}
},
"id":  242,
"type":  "Vsts",
"name":  "TestUpdate",
"description":  "",
"isShared":  false,
"variableGroupProjectReferences":  [
{
"projectReference":  "@{id=0add8cd8-0fc8-4aca-8eb4-164cd8d09c9d; name=AutoUpdateVariableGroups}",
"name":  "TestUpdate",
"description":  ""
}
]
}

文档说明更新url为:

PUT https://{instance}/{collection}/_apis/distributedtask/variablegroups/{groupId}?api-version=6.0-preview.2

请求体具有上述json值(没有ID,因为这是在URI中)。所以update json变成:

$body = @"
{
"variables":  {
"checkupdated":  {
"value":  "valueupdated"
}
},
"type":  "Vsts",
"name":  "TestUpdate",
"description":  "",
"isShared":  false,
"variableGroupProjectReferences":  [
{
"projectReference":  "@{id=0add8cd8-0fc8-4aca-8eb4-164cd8d09c9d; name=AutoUpdateVariableGroups}",
"name":  "TestUpdate",
"description":  ""
}
]
}
"@

我把它从json转换过来看看是否有效(没有错误)。

并在我的PUT请求中使用它:

$invRestMethParams = @{
Uri = "https://xxx.xxx.nl/tfs/DefaultCollection/_apis/distributedtask/variablegroups/242/?&api-version=6.0-preview.2"
Method = 'PUT'
ContentType = 'application/json'
Body = $body
}
Invoke-RestMethod @invRestMethParams -UseDefaultCredentials

我收到的错误是:

Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Object reference not set to an instance of an object.","typeName":"System.NullReferenceException, mscorlib","typeKey":"NullReferenceException","errorCode":0,"eventId":0}
At line:32 char:1
+ Invoke-RestMethod @invRestMethParams -UseDefaultCredentials
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

不知道如何解决这个问题,有人知道如何解决这个问题吗?似乎我忘记了一个值,但我有点迷失了这里的问题是什么。

从您的脚本来看,似乎它与您的请求体有问题。

在projectReference字段中,需要用,代替;,并且需要修改格式。

"projectReference": {"id":"projectID", "name":"projectname"},

参考我的示例:

$JSON = @"
{

"variables": {
"checkupdate": {
"value": "vaslueupdate"
}
},
"type": "Vsts",
"name": "AA",
"description": "",
"isShared": false,
"variableGroupProjectReferences": [
{

"projectReference": {"id":"108e4d7c-0bf3-4940-80da-4793f83def92", "name":"kevin1012"},
"name": "AA",
"description": ""
}
]

}
"@

最新更新