【问题标题】:import Azure Devops pipeline variables from json file从 json 文件导入 Azure Devops 管道变量
【发布时间】:2020-02-24 02:55:58
【问题描述】:

我想使用 json 文件来存储 powershell 脚本使用的变量。在我配置了管道的 azure devops 中,管道包含 powershell 脚本,其中包含变量列表。我想使用 json 文件并将所有变量存储在这个文件中。我想将 json 文件存储在 Azure 存储库中,并在管道启动后使用它。我不想使用变量组。我找到了这个解决方案 [Json to Variable]https://marketplace.visualstudio.com/items?itemName=OneLuckiDev.json2variable&targetId=02fbae5c-cc01-4c8b-a90f-7393a3156347,但我读到了一些关于这个任务的不恭维的意见。有什么方法可以使用 json 文件作为存储变量的地方,或者我可以使用不同的文件格式? 更新:

【问题讨论】:

  • 这个扩展有什么问题?试一试,然后问。
  • 为什么不直接用powershell读取json文件呢?如果您想将这些设置为在管道的后续步骤中使用的环境变量,那么 echo 变量如下:echo "##vso[task.setvariable variable=a]20" : docs.microsoft.com/en-us/azure/devops/pipelines/process/…

标签: json azure-devops azure-pipelines azure-powershell


【解决方案1】:

为什么不直接使用 Powershell 内置 cmdlet:ConvertFrom-Json。请参阅有关此 cmdlet 说明的官方文档:Powershell: ConvertFrom-Json

您可以添加脚本:

Get-Content "{JSON file path}" | out-string | ConvertFrom-Json

Get-Content 会将 JSON 文件读入字符串数组,ConvertFrom-Json 将这些字符串转换为 PSCustomObject 对象。然后你可以用简单的杠杆点表示法(.)调用确切的对象,然后在任务脚本中使用这种格式。

这是一个简单的示例可以供您参考:

$data = Get-content {your JSON file path}| out-string | ConvertFrom-Json
Write-Output $data.ts

在这里,我在本地 Powershell-ISE 中进行了尝试,这与 Powershell 任务中的用法相同。 ts 是我的 JSON 对象之一。在 azure devops 中,如果将文件存储在 Repos 中,则可以使用 $(Build.SourcesDirectory)\..\..\...json 之类的路径来指定文件位置。

【讨论】:

  • 嗨,这正是我正在寻找的,我已经使用管道内联脚本对此进行了测试,它工作正常。谢谢!!
  • 还有一个问题,为什么我仍然收到错误消息“Get-Content : Cannot find path 'D:\Variables.json' because it does not exist.”。我使用管道内联脚本测试了这个解决方案,它工作正常。现在在我的 powershell 脚本中,我正在使用这个 --> $JsonFilePath = "$($Build.SourcesDirectory)\Variables.json" $JsonDataBase = Get-Content $($JsonFilePath) | out-string | ConvertFrom-Json 并遇到错误,文件存储在 devops repo 中。
  • @tester81。根据您的脚本配置,我假设您的 Variable.json 位于您的存储库的根路径中,对吧?将路径脚本更改为$JsonFilePath = "$(Build.SourcesDirectory)\Variables.json" $JsonDataBase = Get-Content $JsonFilePath | out-string | ConvertFrom-Json。你使用的方法不正确,因为正确的路径值应该是d:\a\1\s\...而不是D:\....
  • 好的,我刚刚更正了,现在我有$JsonFilePath = "$(Build.SourcesDirectory)\Variables.json",但还是有问题,现在出现错误,例如 --> D:\a\1\s\Get-RbacReport.ps1 : The term 'Build.SourcesDirectory' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
  • @tester81。这是我的 powershell 上的简单示例:imgur.com/a/Rc0SVsW。如果方便,你能告诉我你的脚本是什么样的吗?
猜你喜欢
  • 2019-04-30
  • 2021-11-23
  • 1970-01-01
  • 2021-12-07
  • 2019-04-29
  • 1970-01-01
  • 2021-11-23
  • 2021-11-23
  • 1970-01-01
相关资源
最近更新 更多