【问题标题】:Vsts pass variable as array of objectsVsts 将变量作为对象数组传递
【发布时间】:2024-01-07 03:29:01
【问题描述】:

我正在尝试将变量作为对象数组传递给释放管道。 目标是在我的appsettings.json 中拥有类似

"myArrayObject": [
      {
        "host": "localhost:2948",
        "protocol": "http"
      }
    ]

在变量选项卡中,我创建了名为 myArrayObject 的变量并分配给它

[{'host':'someUrl','protocol':'https'},{'host':'localhost:44394','protocol':'https'}]

不知何故,该变量未被释放,所以我将此脚本添加到管道中

powershell -command "&{
 $json = Get-Content '.\appsettings.json' -raw | ConvertFrom-Json;
 $json.myArrayObject = '$(myArrayObject)';
 $json | ConvertTo-Json -Depth 32 | Set-Content '.\appsettings.json'; 
 }"

然后我得到了错误

Missing type name after '['.
At line:1 char:129
+ ... llowedUris = [{'host':'someUrl','protoc ...
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token ':'someUrl'' in expression or 
statement.
At line:1 char:169
+ ... lowedUris = [{'host':'someUrl','protoco ...

有什么方法可以实现吗?将对象数组作为变量传递?

我也试过这种方法:

powershell -command "&{
 $json = Get-Content '.\appsettings.json' -raw | ConvertFrom-Json;
 $json.myArrayObject = '[{"host":"someUrl","protocol":"https"},{"host":"localhost:44394","protocol":"https"}]';
 $json | ConvertTo-Json -Depth 32 | Set-Content '.\appsettings.json'; 
 }"

但最后我得到了:

"myArrayObject" : "[{host:someUrl,protocol:https},{host:localhost:44394,protocol:https}]"

【问题讨论】:

    标签: powershell azure-devops azure-pipelines-release-pipeline azure-artifacts


    【解决方案1】:

    这是解决方案:

    powershell -command "&{
        $json = Get-Content '.\appsettings.json' -raw | ConvertFrom-Json;
         $data = '$(additionalAllowedUris)' | ConvertFrom-Json;
         $json.additionalAllowedUris= $data.SyncRoot;
         $json | ConvertTo-Json -Depth 32 | Set-Content '.\appsettings.json';
        }"
    
    [{ \"host\" : \"someUrl\",\"protocol\" : \"https\"},{ \"host\":\"localhost:44394\",\"protocol\" : \"https\"},{ \"host\":\"someUrl2\",\"protocol\" : \"https\"}]
    

    【讨论】:

    • 很高兴看到您解决了这个问题。请尽可能Accept it as an Answer,这对阅读此主题的其他社区成员会有所帮助。
    • 我会,但允许 2 天后