Carlos Huchim
Carlos Huchim

Reputation: 102

Update build variable using powershell in tfs

I'm using Visual Studio TFS Services and want to run a powershell, update a variable and use it in another task.

My build definition only has 2 powershell tasks and 1 variable (NugetEnabled) with default value "dontpush".

Build variables: NugetEnabled (value: "dontpush")

Task 1: Powershell Script

##vso[task.setvariable variable=NugetEnabled;]push

Task 2: Powershell Script

$value= $env:NugetEnabled

if ($value)
{
    Write-Output "Value of the nuget is set and equals to $value"
}
else
{
    Write-Output "Value of the nuget doesn't exists."
}

The output console writes:

"Value of the nuget is set and equals to dontpush"

Expected value: "push".

I'm not able to update the value. I want to update the value because I want to use a "Custom condition" to push my nuget package.

The complete powershell script is hosted in github and my agent version is 2.116.1

Thanks in advance! Any advice will be apreciated and useful.

Upvotes: 1

Views: 6127

Answers (1)

David BRU
David BRU

Reputation: 9

In fact, i'm using TFS 2017 and library for powershell vsts task :

github.com/Microsoft/vsts-task-lib/tree/master/powershell

So, it becomes really simple to use variable shared between build/release Task.

Example (importing the ps module) :

$Script_Path = $PSScriptRoot
Import-Module $script_Path"\VstsTaskSdk\VstsTaskSdk.psd1" -force #2>&1> $null

$Root_Path =  $ENV:ROOT_PATH
$Repo_Path = $ENV:BUILD_SOURCESDIRECTORY
$Repo_Branch = $ENV:BUILD_SOURCEBRANCHNAME
$Repo_CID = $ENV:BUILD_CID
$Log_Folder = $ENV:LOG_FOLDER
$SCRIPT_DB = $ENV:SCRIPT_DB
$Build_result_folder = $ENV:BUILD_RESULT_FOLDER



$Artifact_Path=$ENV:BUILD_ARTIFACTSTAGINGDIRECTORY
write-host "Artifact_Path : "$($Artifact_Path)  -backgroundcolor "Red"

$File_Log = $Log_Folder+"\LOG-TFS-"+$ENV:BUILD_BUILDNUMBER+".log"
Write-Host "Fichier de log : "$FileLog -backgroundcolor "Red"
Set-VstsTaskVariable -Name "LOG_FILE" -Value $File_Log  #2>&1> $null

To set variable value : Set-VstsTaskVariable

To get variable value : Get-VstsTaskVariable

To get variable value, as well, you can use the environment variable automatically exported by TFS, the naming convention for build-in variable change when use in ps script, there is to convert the name "." to "_".

example : $ENV:BUILD_SOURCEBRANCHNAME become Build.SourceNameBranche in TFS UI interface. Otherwise, define your own variable in TFS and use it in PS as my example, $ENV:... without naming conversion.

Build Variable details : https://www.visualstudio.com/en-us/docs/build/define/variables

Release Variable details : https://www.visualstudio.com/en-us/docs/build/concepts/definitions/release/variables

Upvotes: 1

Related Questions