I have the following variable:
Name: TestVar
Value: xxx
And the following script:
$testVar=$env:TestVar.ToLower()
if($testVar-eq 'xxx'){
$testVar= 'updated'
Write-Host "##vso[task.setvariable variable=TestVar;]$testVar"
The value after a run remains xxx
instead of updated
.
The syntax of "##vso[task.setvariable variable=TestVar;]$testVar"
is to update the variable value only for this build running, not for future builds.
If you want to update the build variable list you need to update the build definition with Rest API .
An example of a PowerShell script that does it:
$head = @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }
$url="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/definitions/$(System.DefinitionId)?api-version=5.0"
$build = Invoke-RestMethod -Uri $url -Method Get -Headers $head -ContentType application/json
$build.variables.TestVar.value = "updated"
$json = $build | ConvertTo-Json -Depth 10
Invoke-RestMethod -Uri $url -Method Put -Headers $head -Body $json -ContentType application/json
If you want to make the change permanent you need to do it via the api as follows, otherwise its just for the duration of the run
$projecturi = "$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"
$project = "$env:SYSTEM_TEAMPROJECT"
$accessToken = $env:SYSTEM_ACCESSTOKEN
$buildID = "$env:BUILD_BUILDID"
$headers = @{ "Authorization" = "Bearer $accessToken" }
$buildurl= $projecturi + $project + "/_apis/build/builds/" + $buildID + "?api-version=2.0"
Write-Host $buildurl
$getbuild = Invoke-RestMethod -Uri $buildurl -headers $headers -Method Get |select definition
Write-Host $getbuild
$definitionid = $getbuild.definition.id
Write-Host $definitionid
$defurl = $projecturi + $project + "/_apis/build/definitions/" + $definitionid + "?api-version=2.0"
$definition = (Invoke-WebRequest $defurl -Headers $headers -Method GET -ContentType "application/json" -UseBasicParsing).Content | ConvertFrom-Json
$definition.variables.testvar.value = "Updated"
$json = @($definition) | ConvertTo-Json -Depth 100
Try{
$result = (Invoke-WebRequest $defurl -Method "Put" -Headers $headers -ContentType "application/json" -Body $json -UseBasicParsing).Content | ConvertFrom-Json
}
Catch{
$errorMessage = $_.Exception.Message
$errorDetail = $_
$message = @"
$errorMessage
$errorDetail
"@
Write-Error $message -ErrorAction Continue
return 0
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.