代码之家  ›  专栏  ›  技术社区  ›  GTGabaaron

Azure Pipelines-使用powershell将变量值插入json

  •  0
  • GTGabaaron  · 技术社区  · 2 年前

    我在Azure Pipelines(非内联)中工作,在那里我试图将变量的值插入JSON文件,提到的文件是从存储帐户下载并在过程中读取的,到目前为止还不错。这些文件包含以下内容

    {"MedUnits":[
        {
            "System":"Med",
            "UnitName":"MedicalUnitEast",
            "MedID":"",
            "Assigments":[
            {
                "Measur":"Density",
                "Unit":"m3"
            },
            {
                "Measur":"Weight",
                "Unit":"kg"
            }
        ]}
    ]}
    

    我需要插入始终为空的MedID密钥的变量值,我一直在尝试不同的方法(math/replace,if),但我在某些cmdlet中遇到了错误。这是我尝试过的一个例子:

    #Downloading file from storageaccount
    $unitsFile = Invoke-WebRequest -URI "https://storage.blob.core.windows.net/folder/${json}?sv=TOKEN"
    
    $JsonData = Get-Content -Path .\$unitsFile | ConvertFrom-Json
    $JsonData.update | % { if($JsonData.MedUnits.MedID){
                                        $JsonData.MedUnits.MedID= "$ID"
                                }
                            }
    $JsonData | ConvertTo-Json -Depth 4  | set-content $unitsFile 
    

    当我犯错的时候,我好像做错了什么” ##[error]获取内容:路径中存在非法字符。 “在管道执行期间,如果我删除 路径(反斜杠) 在获取内容之后,我收到另一个错误,说明 ##[error]获取内容:找不到驱动器。名为“{”MedUnits“”的驱动器不存在。

    0 回复  |  直到 2 年前
        1
  •  1
  •   SiddheshDesai    2 年前

    我在本地和Azure管道Powershell任务中尝试了以下代码,MedID已成功更新。在运行脚本时,请确保Json文件的路径是正确的。

    地方的

    剧本

    $unitsFile="C:\Logic-app\Medunits.json"
    $ID="1233"
    
    $JsonData = Get-Content -Path $unitsFile -Raw | ConvertFrom-Json
    $JsonData.MedUnits[0].MedID = $ID
    $JsonData | ConvertTo-Json -Depth 4 | Set-Content $unitsFile
    

    输出

    enter image description here

    enter image description here

    Azure DevOps Powershell任务:-

    trigger:
    - main
    
    pool:
      vmImage: ubuntu-latest
    
    steps:
    
    - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: |
          $unitsFile="$(System.DefaultWorkingDirectory)/Medunits.json"
          $unitsFile
          $ID="1244"
          
          $JsonData = Get-Content -Path $unitsFile -Raw | ConvertFrom-Json
          $JsonData.MedUnits[0].MedID = $ID
          $JsonData | ConvertTo-Json -Depth 4 | Set-Content $unitsFile
          $JsonData
    

    输出

    enter image description here

    推荐文章