Retrosec6
Retrosec6

Reputation: 179

How two concatenate environment variables names in powershell

Say I have the following environment variables:

a = Poke
b = mon
Pokemon= Feraligatr

I want to be able to concatenate a and b environment variables to get the variable name Pokemon and the get Pokemon value like $($env:ab) or $($env:$($env:a)$($env:b)) (This examples does not work)

Upvotes: 2

Views: 408

Answers (1)

mklement0
mklement0

Reputation: 440047

Building on the helpful comments:

You're looking for indirection, i.e. the ability to refer to an environment variable indirectly, via another (environment) variable(s) storing the target variable's name.


PowerShell-idiomatic solution:

Use the Env: drive in combination with the Get-Content cmdlet:

# The target environment variable.
$env:Pokemon='bingo!'

# The variables that, in combination, return the *name* 
# of the target environment variable.
$env:a = 'Poke'
$env:b = 'mon'

# Use Get-Content and the env: drive to retrieve
# an environment variable by an *indirectly* specified name.
# Note: 
#   * env:$env:a$env:b is treated like "env:$env:a$env:b",
#     i.e. an expandable (interpolating string).
#   * For better visual delineation of the variables, use:
#       env:${env:a}${env:b}
#   * `-ErrorAction Ignore` ignores the case when the target var.
#     doesn't exist (quietly returns $null`)
# -> 'bingo!'
Get-Content -ErrorAction Ignore env:$env:a$env:b 

# Alternative, with explicit string concatenation.
Get-Content -ErrorAction Ignore ('env:' + $env:a + $env:b)

Note:

  • To set environment variables indirectly, use the Set-Content cmdlet; e.g.:

    $varName = 'FOO'
    Set-Content env:$varName BAR # $env:FOO now contains 'BAR'
    
  • Applying the same technique to regular shell variables (non-environment variables), requires either use of the variable: drive, or, for more flexibility, the Get-Variable and Set-Variable cmdlets - see this answer.

  • More more information about expandable (interpolating) string literals such as "env:$env:a$env:b", see the conceptual about_Quoting help topic.


.NET API alternative:

As Max points out, you can also use the static System.Environment.GetEnvironmentVariable .NET method:

[Environment]::GetEnvironmentVariable("${env:a}${env:b}")

For more information about calling .NET API methods from PowerShell, see the conceptual about_Methods help topic.

Upvotes: 1

Related Questions