Jay Pat
Jay Pat

Reputation: 35

TeamCity user defined environment variables

I am trying to get user defined variables from TeamCity parameters which I set during runtime via PowerShell.

When I do %variablename% in PowerShell runner script window I get the value of the variable. However when I programmatically build a string with % sign it prints the literal. I have also tried using $env:variablename as per their documentation which does not help.

Below is the function I am writing to get the value of the env variable:

Function get-tc-env-var {

Param (
[Parameter(Mandatory=$true)]
[string]$env_var

  )
Process        
{

$var = Env:$env_var # tried both $Env and Env both dont work
                if (!$var)
                {

                Write-Host "Can't get environment variable:" $env_var

                }
                else { return $Var.trim()}
                    }
                     }

Upvotes: 1

Views: 1492

Answers (1)

Mark Wragg
Mark Wragg

Reputation: 23355

If you want to get an environment variable by specifying its name through another variable you need to use Get-Item:

Function get-tc-env-var {

    Param (
        [Parameter(Mandatory=$true)]
        [string]$env_var
    )
    Process        
    {
        $var = (Get-Item env:$env_var).value

        if (!$var)
        {
            Write-Host "Can't get environment variable:" $env_var
        }
        else
        { 
            return $Var.trim()
        }
    }
}

Upvotes: 1

Related Questions