Azure DEVOPS-更新json文件-PowerShell脚本 [英] Azure devops - update json file - powershell script

查看:0
本文介绍了Azure DEVOPS-更新json文件-PowerShell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了PowerShell脚本来使用变量更新json文件。JSON文件位于Azure devopsrepo中,json文件名为var.json。 我将在azure devop中使用此解决方案,因此我构建了管道并在azure devop的Variables选项卡中设置了测试变量:

在我的脚本中,我有参数和变量块,如下所示:

param(
    [Parameter (Mandatory=$true)]
    [String] $FileRes
)
#env variable
$Path = $Env:BUILD_SOURCESDIRECTORY

# Download variables from Json file
$JsonBase = @()
$JsonPath = "$PathVar.json"
$JsonBase = Get-Content $JsonPath | out-string | ConvertFrom-Json

$JsonBase.FileNames[0].value = $FileRes
在我的脚本中,我使用命令$JsonBase | ConvertTo-Json | Set-Content -Path $JsonPath将输出定向到json文件。

JSON文件结构:

{
    "FileNames":  [
                      {
                          "value":  "AAAbbbccc123",
                          "value1":  "www",
                          "value3":  "swd",
                          "value4":  "xvb"
                      }
                  ]
}
结束时管道的状态为OK,所有步骤均为绿色,但var.json文件未按我的要求进行更新。仍有旧值-->"value": "AAAbbbccc123"

推荐答案

实际上,它已被替换,但您需要在输出报告中查看此更改。

为了更清楚,您可以使用私有代理来运行此生成。然后转到相应的本地报告,并在构建完成后检查Var.json文件:

在您的脚本中,Set-Content$(Build.SourcesDirectory)Var.json下的文件,而不是VSTS repos中存储的文件。因此,若要查看是否已成功更换,请转到您的output repos,即代理中的那个。

有时,如果您使用的是托管代理,您可能无法查看详细的输出报告,因为主机映像将在管道完成后由服务器回收。

此时,您可以在其中添加另一个脚本,将JSON文件内容打印出来,然后可以检查是否成功替换:

$content= Get-Content -Path $JsonPath
Write-Host $content


此外,请对您的脚本稍作更改:

$JsonBase.FileNames[0].value = "$(FileRes)"

此处请使用$(FileRes)而不是$FileRes,因为您在变量选项卡中指定值。别忘了双引号""

更新:

若要将输出Repos更改回VSTS Repos,请尝试执行以下操作:

(1)第一个命令行任务:

git config --global user.email "xxx@xx.com"
git config --global user.name "Merlin"

cd $(Build.SourcesDirectory)
git init

(2)在PowerShell任务中,执行set-content脚本。

(3)在第二个命令行任务中,执行git push以推送更改:

git add Var.json
git commit -m "aaaa"
git remote rm origin
git remote add origin https://xxx@dev.azure.com/xxx/xxx/_git/xxxx
git push -u origin HEAD:master

此外,要在管道中成功运行git脚本。在启用"Allow脚本to Access......."旁边您还应该遵循此权限设置。

这篇关于Azure DEVOPS-更新json文件-PowerShell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆