Access all available build variables from your VSTS Build task

2016-03-09

NOTE: This cmdlet works with the Powershell host that shipped with TFS 2015 RTM and which will be replaced with a new task runner. Whether this functionality will remain, is uncertain.

If you want to know which variables are available during your build, or if you want people to create variables with a specific prefix and want to do anything with that, then you need access to the list of all available variables.

Though it's easy to access a specific variable by name using the Get-Variable cmdlet, it's not so easy to access all variables. Plus, the Get-Variable command only works when you know the full name beforehand.

Using the below function you receive a dictionary with the name and current value of each variable. You can use it to build tasks that use convention over configuration and retrie a list of all variables that start with a prefix you expect:

$MyVariables = (Get-Variables $distributedTaskcontext).Keys | ?{ $_.StartsWith("MyPrefix.") }

Use te cmdlet below to fetch all variables and do with them what you like:

function Get-Variables{
    param
    (
        $distributedTaskContext
        [switch] $safe = $false
    )
    begin
    {
        Write-Debug "Entering: Get-Variables"
        
        $type = [Microsoft.TeamFoundation.DistributedTask.Agent.Interfaces.IServiceManager] 
        $variableService = $type.GetMethod("GetService").MakeGenericMethod([Microsoft.TeamFoundation.DistributedTask.Agent.Interfaces.IVariableService]).Invoke($distributedTaskContext, @())
        $dictionary = New-Object "System.Collections.Generic.Dictionary[string,string]" ([System.StringComparer]::OrdinalIgnoreCase)
    }
    process
    {
        if ($safe.IsPresent)
        {
            $variableService.MergeSafeVariables($dictionary)
        }
        else
        {
            $variableService.MergeVariables($dictionary)
        }
    }
    end
    {
        Write-Debug "Leaving: Get-Variables"
        return $dictionary
    }
}

I used this little snippet to create a new build task which can expand the value of nested variables. You can find it here:

 

Search This Blog

Loading...

Most Reading