parameters:
- name: VariableName
  displayName: Variable Name
- name: VariableValue
  displayName: Variable Value

steps:
- task: PowerShell@2
  displayName: Update Pipeline Variable - ${{parameters.VariableName}}
  env:
    SYSTEM_ACCESSTOKEN: $(System.AccessToken)
  inputs:
    targetType: inline
    script: |
      [string]$CollectionUri = $env:SYSTEM_COLLECTIONURI
      [string]$ProjectName = $env:SYSTEM_TEAMPROJECT
      [string]$DefinitionId = $env:SYSTEM_DEFINITIONID
      [string]$VariableName = '${{parameters.VariableName}}'
      [string]$VariableValue = '${{parameters.VariableValue}}'
      [string]$AccessToken = $env:SYSTEM_ACCESSTOKEN

      if ($CollectionUri.EndsWith('/')) {
        $CollectionUri = $CollectionUri.TrimEnd('/')
      }

      $headers = @{ 
        'Authorization' = "Bearer $AccessToken"
      }

      [Net.ServicePointManager]::SecurityProtocol = "Tls12, Tls13"

      # Get an overview of the build definition
      $definitionUrl = "$CollectionUri/$ProjectName/_apis/build/Definitions/$($DefinitionId)?api-version=5.0"
      $definitionResponse = Invoke-RestMethod -Method Get -Uri $definitionUrl -Headers $headers -UseBasicParsing

      # If the build has the variable, update it.
      if ($definitionResponse.variables.$VariableName) {
        $oldValue = $definitionResponse.variables.$VariableName.value
        $definitionResponse.variables.$VariableName.value = $VariableValue

        Write-Output -InputObject "Updating $VariableName from $($oldValue) to $($VariableValue)..."

        $body = ConvertTo-Json -InputObject $definitionResponse -Depth 100 -Compress
        $response = Invoke-RestMethod -Method Put -Uri $definitionUrl -Headers $headers -ContentType 'application/json' -Body $body -UseBasicParsing
      }
    pwsh: true
