FlowSoft.DevOps.psm1

Function Add-EnvironmentPieplineVariable {
    param
    (
        [Parameter(Mandatory = $true)]
        $VariableValue,
        [Parameter(Mandatory = $true)]
        [string] $VariableKey
    )
    Write-Host "ensure Variable $VariableKey"
    $apiUrl = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)/$($env:SYSTEM_TEAMPROJECTID)/_apis"
    
    $releaseDefinitionUrl = "$apiUrl/release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.1"
    
    $definition = Invoke-RestMethod -Method GET -Uri $releaseDefinitionUrl -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }
    
    $environment = $definition.environments | Where-Object { $_.Id -eq $env:RELEASE_DEFINITIONENVIRONMENTID }
    if ($null -eq $environment.variables.$VariableKey) {
        Write-Output "add variable: $VariableKey"
        $environment.variables | Add-Member -NotePropertyName $VariableKey -NotePropertyValue "test"
    }
    $environment.variables.$VariableKey = [PSCustomObject]@{value = "$VariableValue" }
    
    $json = $definition | ConvertTo-Json -Depth 100
    Invoke-RestMethod -Uri $releaseDefinitionUrl -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }

    $releaseUrl = "$apiUrl/release/releases/$($env:RELEASE_RELEASEID)?api-version=5.1"


    $release = Invoke-RestMethod -Uri $releaseurl -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }

    $environment = $release.environments | Where-Object { $_.id -eq $env:RELEASE_DEFINITIONENVIRONMENTID }
    
    Write-Host  $environment

    if ($null -eq $environment.variables.$VariableKey) {
        Write-Output "add variable: $VariableKey"
        $environment.variables | Add-Member -NotePropertyName $VariableKey -NotePropertyValue "test"
        Write-Host "1"
    }
    Write-Host "2"
    $environment.variables.$VariableKey = [PSCustomObject]@{value = "$VariableValue" }

    Write-Host "3"

    $json = $release | ConvertTo-Json -Depth 100
    Write-Host "4"
    Write-Host $json
    Write-Host "5"
    Invoke-RestMethod -Uri $releaseurl -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }
    Write-Host "6"
}