Blog

Access all available build variables from your VSTS Build task

04 Apr, 2016
Xebia Background Header Wave
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:

Jesse Houwing
Jesse is a passionate trainer and coach, helping teams improve their productivity and quality all while trying to keep work fun. He is a Professional Scrum Trainer (PST) through Scrum.org, Microsoft Certified Trainer and GitHub Accredited Trainer. Jesse regularly blogs and you'll find him on StackOverflow, he has received the Microsoft Community Contributor Award three years in a row and has been awarded the Microsoft Most Valuable Professional award since 2015. He loves espresso and dark chocolate, travels a lot and takes photos everywhere he goes.
Questions?

Get in touch with us to learn more about the subject and related solutions

Explore related posts