Home > Enterprise >  Assign Value To Variable After Extracting From Json File Using Powershell
Assign Value To Variable After Extracting From Json File Using Powershell

Time:04-25

I have the below json file

{
    "name": "ca",
    "version": "5.2.0"
}

I am extracting the value of version and trying to assign it to a variable ver

$jsonString = Get-Content -Path ./package.json
$jsonObj = $jsonString | ConvertFrom-Json

echo $jsonObj.version

Write-Host "##vso[task.setvariable variable=ver]$jsonObj.version"

echo $ver

Below is the output

5.2.0

I am expecting the value to be printed twice and also get it assigned to the variable ver but it is not getting assigned

CodePudding user response:

If you are trying to use it in builds, you will not see a new value in the same step. Additionally, use $($jsonObj.version) in the logging command:

steps:
- powershell: |
   
   $jsonString = Get-Content -Path ./package.json
   $jsonObj = $jsonString | ConvertFrom-Json
   
   $jsonObj.version
   
   Write-Host "##vso[task.setvariable variable=my.ver]$($jsonObj.version)"

  displayName: 'Set vars'

- powershell: |
   $ver = '$(my.ver)'
   
   $ver
   
  displayName: 'Read vars'
  • Related